我想用两个列表作为键创建一个字典
regions = ['A','B','C','D']
subregions = ['north', 'south']
region_dict = dict.fromkeys(regions, dict.fromkeys(subregions))
这就产生了我想要的正确的措辞:
{'A': {'north': None, 'south': None},
'B': {'north': None, 'south': None},
'C': {'north': None, 'south': None},
'D': {'north': None, 'south': None}}
然而,如果我试图更新这个dict中的一个元素,我会看到其他元素也在更新
region_dict['A']['north']=1
>>> {'A': {'north': 1, 'south': None},
'B': {'north': 1, 'south': None},
'C': {'north': 1, 'south': None},
'D': {'north': 1, 'south': None}}
我不确定我到底做错了什么。如何仅更新此词典中的一个值
只是想让你更清楚
这里
dict.fromkeys(subregions)
这是一个单独的对象(每个键的值都指向该对象),因此每当您使用一个键更改该对象的值时,该值都会反映在引用该对象的所有其他键上要通过代码进行解释,应该是这样的:
因此,当您将
dict.fromkeys(subregions)
放入dict
理解中时,每次都会创建一个新对象。这就是为什么这不会有问题的原因当与每个键一起使用的值是可变的时,不能使用
dict.fromkeys
;它使用与每个键的值相同的别名,因此无论查找哪个键,都会得到相同的值。基本上是the same problem that occurs with multiplying lists of lists。一个简单的解决方案是用dict
理解替换外部dict.fromkeys
:相关问题 更多 >
编程相关推荐