迭代错误期间字典大小变化

Dictionary Size Change During Iteration Error

我正在编写代码通过选择删除字典中的某些项目,甚至使用字典的副本来防止在迭代期间更改其大小,但我不断收到此错误:

'RuntimeError: dictionary changed size during iteration'

import copy
word = {'a':{'aa':{'aaa', 'aab'}, \
             'ab':{'aaa', 'aab'}}, \
        'b':{'ba':{'aaa', 'aab'}, \
             'bb':{'aaa', 'aab'}}, \
        'c':{'ca':{'aaa', 'aab'}, \
             'cb':{'aaa', 'aab'}}}
wordCopy = copy.copy(word)
for item in word.keys():
    for k in word[item].keys():
        print(k)
        print('Enter del to delete this item:')
        deleteCertificate = input()
        if deleteCertificate == 'del':
            del wordCopy[item][k]
word = wordCopy
print(word)

这要归功于您的 copy。它实际上只是一个shallow copy。来自文档:

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

所以当你浅拷贝字典时它仍然有对原始字典的引用。你会看到这一点,如果在你的错误之后,你打印出 word 你会注意到一个元素已从中删除。

相反,您需要 deep copy。再次来自文档:

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

如果替换行,您可以避免错误:

wordCopy = copy.copy(word)

与:

wordCopy = copy.deepcopy(word)

我还建议您完整阅读 docs on copy

您的 wordCopyword 是分开的,但 wordCopy[item]word[item] 是同一个对象,因为 copy.copy 是浅拷贝。

你可以做一个深拷贝,或者你可以只创建一个新的空对象,并在倒置条件下插入需要保留的项目,根本不修改原来的word