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

igr*_*lvr 3 python dictionary

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

regions = ['A','B','C','D']
subregions = ['north', 'south']
region_dict = dict.fromkeys(regions, dict.fromkeys(subregions))
Run Code Online (Sandbox Code Playgroud)

这产生了我想要的正确的字典:

{'A': {'north': None, 'south': None},
 'B': {'north': None, 'south': None},
 'C': {'north': None, 'south': None},
 'D': {'north': None, 'south': None}}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试更新此 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}}
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*ger 10

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

region_dict = {region: dict.fromkeys(subregions) for region in regions}
Run Code Online (Sandbox Code Playgroud)