python3 RuntimeError: dictionary changed size during iteration
python2
keys
先对字典进行 copy,从而在修改字典时,也能进行迭代
headerTable = {}
minSup = 1
for k in headerTable.keys():
if headerTable[k] < minSup:
del(headerTable[k])
python3
Python 3.x 的 keys
返回的是iterator 而非列表,导致当修改字典时,无法迭代。所以,可以使用list
强制将字典进行copy,转换成列表。
headerTable = {}
minSup = 1
for k in list(headerTable):
if headerTable[k] < minSup:
del(headerTable[k])
How to avoid “RuntimeError: dictionary changed size during iteration” error?