更新嵌套字典中的值-Python [英] Update value in nested dictionary - Python

查看:201
本文介绍了更新嵌套字典中的值-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)}

这篇关于更新嵌套字典中的值-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆