简体   繁体   English

更新嵌套字典中的值-Python

[英]Update value in nested dictionary - Python

I created a dictionary as follows: 我创建了一个字典,如下所示:

gP = dict.fromkeys(range(6), {'a': None, 'b': None, 'c': None, 'd': None})

Now, when I try to modify a value doing: 现在,当我尝试修改值时:

gP[0]['a'] = 1

for some reason, all the values of a (regardless of the key they belong to) change to 1 as shown below: 出于某种原因,所有的值a (无论键的它们属于)变化为1,如下所示:

{0: {'a': 1, 'b': None, 'c': None, 'd': None},
 1: {'a': 1, 'b': None, 'c': None, 'd': None},
 2: {'a': 1, 'b': None, 'c': None, 'd': None},
 3: {'a': 1, 'b': None, 'c': None, 'd': None},
 4: {'a': 1, 'b': None, 'c': None, 'd': None},
 5: {'a': 1, 'b': None, 'c': None, 'd': None}}

What I am doing wrong? 我做错了什么? What's the proper assignment statement? 什么是正确的作业说明?

As @deceze said, Python doesn't make copies. 正如@deceze所说,Python不会复制。 You are referencing the same dict in all the value parts of the key-value pairs. 您在键值对的所有值部分中引用相同的dict。

An alternative would be: 一种替代方法是:

gP = {x: {'a': None, 'b': None, 'c': None, 'd': None} for x in range(6)}

Update : There is a much cleaner version of this answer by @Chris_Rands : 更新@Chris_Rands给出了这个答案的更干净的版本:

{x: dict.fromkeys('abcd') for x in range(6)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM