通过更改其他键更新Python中的字典

2024-05-23 14:31:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用两个列表作为键创建一个字典

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}}

我不确定我到底做错了什么。如何仅更新此词典中的一个值


Tags: none元素列表字典regiondict词典regions
2条回答

只是想让你更清楚

这里dict.fromkeys(subregions)这是一个单独的对象(每个键的值都指向该对象),因此每当您使用一个键更改该对象的值时,该值都会反映在引用该对象的所有其他键上

要通过代码进行解释,应该是这样的:

temp = dict.fromkeys(subregions)
region_dict = {region: temp for region in regions}

因此,当您将dict.fromkeys(subregions)放入dict理解中时,每次都会创建一个新对象。这就是为什么这不会有问题的原因

当与每个键一起使用的值是可变的时,不能使用dict.fromkeys;它使用与每个键的值相同的别名,因此无论查找哪个键,都会得到相同的值。基本上是the same problem that occurs with multiplying lists of lists。一个简单的解决方案是用dict理解替换外部dict.fromkeys

region_dict = {region: dict.fromkeys(subregions) for region in regions}

相关问题 更多 >