【问题标题】:I want to make a single dictionary from a dictionary of dictionary in python [duplicate]我想从python中的字典字典中制作一个字典[重复]
【发布时间】:2019-06-19 12:49:27
【问题描述】:

我有字典,其中包含字典作为其键的值。我想从中创建一个字典,如果有重复的键,它应该添加这些键的值

所以我有

temp_dict = {0: {'a':1, 'b':2}, 1: {'c':3,'d':4}, 2: {'d':5,'e':6}}

我尝试这样做是为了使其成为单个字典(尽管在此步骤中不添加来自相同键的值)

empty_dict = {}
for d in empty_dict:
    for k,v in d.items():
        empty_dict[k] = v

但上面的代码也显示错误。然后下一步也是添加来自同一个键的值。

我希望输出为

new_dict = {'a':1, 'b':2, 'c':3, 'd':9, 'e':6}

d 有 9 通过添加来自 'd' 上面的值。

【问题讨论】:

  • 你至少尝试过简单的for循环方法吗?
  • 您尝试过的代码在哪里,哪些部分不起作用。人们会很乐意帮助你。但是,这不是免费的代码编写服务。

标签: python pandas dictionary merge nested


【解决方案1】:

您可以使用标准库中的Counter

from collections import Counter

c = Counter()

for i in temp_dict.values():
    c.update(i)

Counter({'a': 1, 'b': 2, 'c': 3, 'd': 9, 'e': 6})

【讨论】:

  • 谢谢。这完美地工作。但是有没有办法不用 counter()
猜你喜欢
  • 2022-11-30
  • 2019-09-26
  • 1970-01-01
  • 2019-05-08
  • 2018-09-18
  • 2019-03-17
  • 1970-01-01
  • 2017-02-28
  • 2013-12-20
相关资源
最近更新 更多