【问题标题】:Updating or adding keys to dicts [duplicate]更新或添加密钥到字典 [重复]
【发布时间】:2013-02-19 17:48:40
【问题描述】:

我有很多 dicts,我给这个例子 2 个:

dict1={'green': 3, 'yellow': 5, 'blue': 1}
dict2={'green': 5, 'yellow': 1, 'blue': 3, 'purple': 10}

我一直在尝试找到一种添加 2 个字典的方法,以便我可以更新现有键的值(总和),并为不存在的键和值相加。

结果:

results = {'green': 8, 'yellow': 6, 'blue': 4, 'purple': 10}

我试过dict1.update(dict2),但如你所知,我只有一本包含更新值的字典,没有总结。

有什么方法可以做到这一点?

更新:

已解决:实际上 collections.Counter 成功了……谢谢

【问题讨论】:

  • 使用 collections.Counter。
  • 您希望重复键发生什么?例如,您是否希望将“绿色”映射到 3、5、3+5 或其他值?
  • @KyleStrand: 3 + 5,参见示例results 字典。
  • @mgilson 感谢 collections.Counter 做到了!

标签: python dictionary bigdata


【解决方案1】:

呃,这太难了……

dicts = [dict1, dict2]
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), []))])

[{'blue': 1, 'green': 3, 'yellow': 5}, {'blue': 3, 'purple': 10, 'green': 5, 'yellow': 1}]

或更具可读性

dicts = [dict1, dict2]
keys = reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), [])
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(keys)])

【讨论】:

    【解决方案2】:
    {x: dict1.get(x,0) + dict2.get(x,0) for x in set(dict1.keys() + dict2.keys())}
    

    输出:

    {'blue': 4, 'purple': 10, 'green': 8, 'yellow': 6}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 2011-03-06
      • 1970-01-01
      • 2022-06-13
      • 2013-01-04
      • 2014-10-31
      • 2018-06-24
      • 2014-10-04
      相关资源
      最近更新 更多