小编igr*_*lvr的帖子

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

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

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)

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

python dictionary

3
推荐指数
1
解决办法
148
查看次数

标签 统计

dictionary ×1

python ×1