dictionary changed size during iteration

python中我们对字典遍历的过程中,对字典进行修改,则会报dictionary changed size during iteration的错误。

如:

d = {'a':1, 'b':2}
for i in d:
    d['c'] = 3

Traceback (most recent call last):
  File "D:/dds-diagnose/test3.py", line 26, in
    for i in d:
RuntimeError: dictionary changed size during iteration

解决方法:

不遍历字典, 只遍历字典的属性名, 那么就避开了这个问题.。

d = {'a': 1, 'b': 2}
for i in d.keys():
    d['c'] = 3

 

 

你可能感兴趣的:(python)