今天寫了這么一段代碼,類似于這樣:
d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
for key in d:
if key == 'three':
del d[key]
這里報(bào)了一個(gè)這樣的錯(cuò)誤:
RuntimeError: dictionary changed size during iteration;
去查了一下,發(fā)現(xiàn)官方的一個(gè)解釋:
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
也就是說在迭代字典的時(shí)候,每次迭代不得循環(huán)刪除或者更新字典。并且提到for k in dict與for k in dict.keys()功能一樣,并且更快。
這個(gè)錯(cuò)誤的解決方式是將keys轉(zhuǎn)化為列表迭代:
keys = list(d.keys())
for key in keys:
if key == 'three':
del(d[key])
字典d返回:
{'one': 1, 'two': 2, 'four': 4, 'five': 5}
歡迎關(guān)注!