“RuntimeError: dictionary change

2017-03-29  本文已影响0人  joy1314bubian
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):
上一篇 下一篇

猜你喜欢

热点阅读