天天看點

python3 RuntimeError: dictionary changed size during iteration

python3 RuntimeError: dictionary changed size during iteration

python2

keys

先對字典進行 copy,進而在修改字典時,也能進行疊代

headerTable = {}
minSup =  
for k in headerTable.keys():
    if headerTable[k] < minSup:
        del(headerTable[k])
           

python3

Python 3.x 的

keys

傳回的是iterator 而非清單,導緻當修改字典時,無法疊代。是以,可以使用

list

強制将字典進行copy,轉換成清單。

headerTable = {}
minSup =  
for k in list(headerTable):
    if headerTable[k] < minSup:
        del(headerTable[k])
           

How to avoid “RuntimeError: dictionary changed size during iteration” error?