Skip to main content
 首页 » 编程设计

python之为什么我不能在迭代另一个字典时修改一个字典(获取更改大小错误)

2025年05月04日16webabcd

我很困惑为什么修改一个已经使用另一个字典创建的字典会导致RuntimeError: dictionary changed size during iteration:

def test(somedict): 
    new = somedict 
    for k,v in somedict.iteritems(): 
        new['test'] = new.pop(k) 
    return new 

>>>test(data) 
Traceback (most recent call last): 
  File "<pyshell#12>", line 1, in <module> 
    test(data[0]) 
  File "<pyshell#10>", line 3, in test 
    for k,v in somedict.iteritems(): 
RuntimeError: dictionary changed size during iteration     

用例:我试图使用查找表替换字典副本中的所有键,并注意到我无法从新字典中弹出()键,我不是迭代。

我意识到使用 somedict.copy():

new = somedict.copy() 

解决问题。但我不明白为什么这在 python 中是非法的。

有人可以解释一下 new = somedict 和 new = somedict.copy() 之间的区别吗?分配变量并不意味着在修改子变量时也修改了派生新分配的数据,至少我是这么想的。

请您参考如下方法:

这是因为 new = somedict 实际上并不意味着它们是内存中的两个独立对象。它们实际上是相同的对象。

但是,当您使用 .copy() 时,您现在正在内存中创建一个允许您操作它的新对象。

str_MemoryID = "Object {0:10} memory location is: {1}" 
str_Contents = "Object {0:10} contents are: {1}" 
 
test = {"one":1, "two":2} 
new = test 
new_copy = test.copy() 
 
# printing the memory ID of the objects 
print(str_MemoryID.format("test", id(test))) 
print(str_MemoryID.format("new", id(new))) 
print(str_MemoryID.format("new_copy", id(new_copy))) 
 
print("\n") 
 
# print the contents of the dictionaries 
 
print(str_Contents.format("test", test)) 
print(str_Contents.format("new", new)) 
print(str_Contents.format("new_copy", new_copy)) 
 
print("\n") 
 
# make a change to the "new" dictionary and let's see what happens 
new['new_item'] = 3 
 
print(str_Contents.format("test", test)) 
print(str_Contents.format("new", new)) 
print(str_Contents.format("new_copy", new_copy)) 
 
print("\n") 
 
# make a change to the "new_copy" dictionary and let's see what happens 
new_copy.popitem() 
 
print(str_Contents.format("test", test)) 
print(str_Contents.format("new", new)) 
print(str_Contents.format("new_copy", new_copy)) 

给出以下输出:

Object test       memory location is: 8606920 
Object new        memory location is: 8606920 
Object new_copy   memory location is: 8606856 
 
 
Object test       contents are: {'one': 1, 'two': 2} 
Object new        contents are: {'one': 1, 'two': 2} 
Object new_copy   contents are: {'one': 1, 'two': 2} 
 
 
Object test       contents are: {'one': 1, 'new_item': 3, 'two': 2} 
Object new        contents are: {'one': 1, 'new_item': 3, 'two': 2} 
Object new_copy   contents are: {'one': 1, 'two': 2} 
 
 
Object test       contents are: {'one': 1, 'new_item': 3, 'two': 2} 
Object new        contents are: {'one': 1, 'new_item': 3, 'two': 2} 
Object new_copy   contents are: {'two': 2}