1

我四处寻找它给我的错误,但我不太明白。他们做了一些事情for k, v in dbdata.items,但这对我也不起作用,它给了我其他错误。

好吧,我要的是删除多个项目。

tskinspath = ['1', '2']   

#
dbdata = {}
dbdata['test'] = {}
dbdata['test']['skins_t'] = {}

# Adds the items
dbdata['test']['skins_t']['1'] = 1
dbdata['test']['skins_t']['2'] = 0
dbdata['test']['skins_t']['3'] = 0
dbdata['test']['skins_t']['4'] = 0

# This doesn't work
for item in dbdata["test"]["skins_t"]:

     if item not in tskinspath:

        if dbdata["test"]["skins_t"][item] == 0:

                    del dbdata["test"]["skins_t"][item]

# exceptions.RunetimeError: dictonary changed size during iteration
4

3 回答 3

1

与其遍历字典,不如遍历dict.items()

for key, value in dbdata["test"]["skins_t"].items():
     if key not in tskinspath:
        if value == 0:
            del dbdata["test"]["skins_t"][key]

在 py3.x 上使用list(dbdata["test"]["skins_t"].items()).

选择:

to_be_deleted = []
for key, value in dbdata["test"]["skins_t"].iteritems():
     if key not in tskinspath:
        if value == 0:
            to_be_deleted.append(key)
for k in to_be_deleted: 
    del dbdata["test"]["skins_t"][k]
于 2013-10-07T11:00:14.467 回答
0

错误消息说:您不应该修改您正在迭代的字典。尝试

for item in set(dbdata['test']['skins_t']):
   ...

这样,您将迭代一个包含所有键的集合dbdata['test']['skins_t']

于 2013-10-07T10:59:38.790 回答
0

由于问题详细信息与问题无关,如果您正在寻找从给定中删除多个键的解决方案,请dict使用此代码段

[s.pop(k) for k in list(s.keys()) if k not in keep]

此外,您可以dict通过理解创建一个新的。

new_dict = { k: old_dict[k] for k in keep }
于 2017-10-10T04:17:42.603 回答