Avatar ·

如何在for循环中从字典中删除值

📁 python, 错误, 示例

我意外地遇到了这样一个问题。在遍历字典的for循环中,我需要从中删除条目,但无论如何都会出现错误:

RuntimeError: dictionary changed size during iteration

我甚至尝试在迭代前创建字典的快照,并遍历副本同时从原字典中删除。

示例:

>>> ot={12:'wqe',13:'wqe',14:'wqe',15:'wqe'}>>> ot1=ot>>> for i in ot1:...  del ot[i]... Traceback (most recent call last):  File ""<stdin>