python 字典嵌套赋值、多个值跟着变化,更新嵌套字典中的值-Python

在尝试修改Python字典中嵌套字典的一个值时,发现所有相同键的值都同步改变。原因在于原始字典的所有值都是引用同一个字典。解决方法是为每个键值对创建独立的字典副本,例如使用dict comprehension。更新后的代码示例给出了正确的赋值方式。
摘要由CSDN通过智能技术生成

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:

{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. You are referencing the same dict in all the value parts of the key-value pairs.

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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值