美文网首页
“RuntimeError: dictionary change

“RuntimeError: dictionary change

作者: joy1314bubian | 来源:发表于2017-03-29 12:31 被阅读0次
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
for i in d:
    if not d[i]:
        d.pop(i)

更改
In Python 2.x calling keys makes a copy of the key that you can iterate over while modifying the dict:

for i in d.keys():

Note that this doesn't work in Python 3.x because keys returns an iterator instead of a list.
Another way is to use list to force a copy of the keys to be made. This one also works in Python 3.x:

for i in list(d):

相关文章

网友评论

      本文标题:“RuntimeError: dictionary change

      本文链接:https://www.haomeiwen.com/subject/evpeottx.html