首页 > 解决方案 > 通过键更改其他键来更新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}}

但是,如果我尝试更新此字典中的一个元素,我会看到其他元素也在更新

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

我不确定我在这里做错了什么。如何仅更新此字典中的一个值?

标签: pythondictionary

解决方案


dict.fromkeys当每个键使用的值是可变的时,您不能使用;它使用与每个键的值相同的别名,因此无论您查找哪个键,您都会获得相同的值。与 list 的乘法列表基本相同的问题。一个简单的解决方案是用理解替换外部:dict.fromkeysdict

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

推荐阅读