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

标签 python dictionary iteration variable-assignment

我很困惑为什么修改一个已经使用另一个字典创建的字典会导致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}   

关于python - 为什么我不能在迭代另一个字典时修改一个字典(获取更改大小错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186818/

相关文章:

python - 从列表中删除空字符串

javascript - 从 bool 字典中提取 object.keys

python-3.x - 组合使用 itertools 和 zip 从两个不同长度的列表创建字典时出现问题

python - 我可以相信 dict 的顺序在每次迭代时都保持不变吗?

python - 如何在 Plotly (python) 中设置背景颜色、标题?

python - 如何回复收件箱中的最后一封电子邮件(IMAP4)?

python - 为什么我的简单线性模型在数据集 g(X) 上学习阈值函数 f(x) = (x > 0) 但在 X 上表现不佳?

android - 离线 map OSM

javascript - JSON 循环子对象

matlab - 如果发生错误,如何在 Matlab 中重复 for 循环迭代