RuntimeError: dictionary changed size during iteration

RuntimeError: dictionary changed size during iteration

错误范例:

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

原因:在遍历过程中对字典进行的操作影响到遍历过程。

解决方法:

1、加上list()

    for k in list(headerTable.keys()):
        if headerTable[k] < minSup:
            del(headerTable[k])

 2、使用要遍历的字典的拷贝,这里使用浅拷贝。如果遍历过程对字典的操作较复杂,建议使用深拷贝

    headerTableCopy=headerTable.copy()  #浅拷贝,拷贝第一层
    for k in headerTableCopy.keys():
        if headerTable[k] < minSup:
            del(headerTable[k])
原文地址:https://www.cnblogs.com/zhhy236400/p/9985123.html