【发布时间】:2020-07-28 22:36:37
【问题描述】:
我想创建一个使用两个列表作为键的字典
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}}
我不确定我到底做错了什么。如何仅更新此字典中的一个值?
【问题讨论】:
-
@zvone:这是相同的症状,但我不认为
list乘法与dict.fromkeys所做的显然相似,至少对于Python 经验较少的人来说。我确实在我的答案中链接了这个问题,但它不是重复的。 -
虽然根本原因非常相似,但我同意这不是一个重复的问题。感谢您提供非常有用的反馈
标签: python dictionary