python - 为什么对 dict2 中的嵌套字典的更改会影响 dict1?

标签 python dictionary nested mutability

<分区>

我不明白这些情况:

content = {'a': {'v': 1}, 'b': {'v': 2}}
d1 = {'k1': {}}
d2 = {'k2': {}}
d1['k1'].update(content)
print(d1)
content['a']['v'] = 3
content['b']['v'] = 4
d2['k2'].update(content)
print(d2)
print(d1)
>>> {'k1': {'a': {'v': 1}, 'b': {'v': 2}}}
>>> {'k2': {'a': {'v': 3}, 'b': {'v': 4}}}
>>> {'k1': {'a': {'v': 3}, 'b': {'v': 4}}}

在上面的例子中,d1 的内容在变量 content 更新后发生了变化。

content = {'a': 1, 'b': 2}
d1 = {'k1': {}}
d2 = {'k2': {}}
d1['k1'].update(content)
print(d1)
content['a'] = 3
content['b'] = 4
d2['k2'].update(content)
print(d2)
print(d1)
>>> {'k1': {'a': 1, 'b': 2}}
>>> {'k2': {'a': 3, 'b': 4}}
>>> {'k1': {'a': 1, 'b': 2}} 

但是在这种情况下,即使变量 content 发生了变化,d1 也不会发生变化。我不明白为什么……有什么想法吗?

最佳答案

参见 shallow vs deep复制。

此处的副本是浅拷贝,因此第一级条目是副本,但嵌套结构是引用。

  • 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.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the
    original.

关于python - 为什么对 dict2 中的嵌套字典的更改会影响 dict1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50445608/

相关文章:

python - 如何将字符串转换为列表?

python - 使用 lambda 和 map 从字典列表中删除键/值

c++ - C++ 映射及其内容的问题

ios - Spotify 返回无效的 NSDictionary

python - 如何获取多个峰值下的面积值

python - 为什么图像中的透明度变成黑色,如何去除它?

python - Matplotlib 连续检查按钮

c++ - (c++) 可以从外部来源嵌套命名空间

java - 在 JSON 中嵌套太深...我应该切换到 XML 吗?

javascript - HTML 中的嵌套类