python - Coping dictionary within a dictionary(嵌套字典)

标签 python dictionary

我有一本像 dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}} 这样的字典(它也有一个字典作为值)。为了某些修改检查目的,我想保持存储这些值相同。所以现在我将这个词典内容复制到另一个词典中作为 dict2 = dict1.copy() .现在我正在更改 dict2 的值喜欢 { 0 : -1, 1 : -2, 2: { 0 : -1, i : -2}} .现在的问题是我的 dict1的字典值也更改为 { 0 : 0, 1 : 1, 2:{ 0 : -1, 1 : -2}} .在这里你可以很容易地看到这个dict1的键 2 值也随着 dict2 的键 2 值而改变。

我应该如何复制 dict2来自 dict1所以如果改变dict2的键 2 值这不应该对 dict1 产生影响的键 = 2 个值?

最佳答案

使用copy.deepcopy执行深拷贝。

关于python - Coping dictionary within a dictionary(嵌套字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347854/

相关文章:

python - 如何在 Tornado 中获取表单 POST 输入?

python - 如何使用 python 更新 mysql,其中字段和条目来自字典?

python - 如何更改具有多个值(元组)的字典的特定值而不出现 TypeError

python - 在字典中进行格式字符串替换

matlab - 导出和导入 MATLAB 映射结构

python - find_elements_by_css_selector 没有给我任何输出,如何处理?

python - Pandas 出现故障?无法覆盖值

python - Tensorflow DNNclassifier : error wile training (numpy. ndarray 没有属性索引)

python - 循环数据时嵌套字典

arrays - 日期字典数组