更新嵌套字典中的值-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
由于某些原因,a
的所有值(无论它们属于哪个键)都变为1,如下所示:
for some reason, all the values of a
(regardless of the key they belong to) change to 1 as shown below:
{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?
答
正如@deceze所说,Python不会复制.您在键值对的所有值部分中引用的是同一个字典.
As @deceze said, Python doesn't make copies. You are referencing the same dict in all the value parts of the key-value pairs.
一种替代方法是:
gP = {x: {'a': None, 'b': None, 'c': None, 'd': None} for x in range(6)}
更新: @Chris_Rands 有一个更干净的答案版本:
Update: There is a much cleaner version of this answer by @Chris_Rands:
{x: dict.fromkeys('abcd') for x in range(6)}