【问题标题】:Updating dictionary in Python by key changing other keys [duplicate]通过更改其他键来更新Python中的字典[重复]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    只是为了让你更清楚。

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

    通过代码来解释,看起来像这样:

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

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

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 1970-01-01
      • 2019-12-04
      • 2016-09-29
      • 2018-11-11
      • 2020-12-27
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多