【问题标题】:Python How to add all values in a 2d Dictionary and return a single dictionary with summed values?Python如何在二维字典中添加所有值并返回一个带有求和值的字典?
【发布时间】:2019-04-10 18:23:50
【问题描述】:

我正在开发的部分程序有一个长度为 n 的2D dict。

字典示例:

test_dict = {
0: {'A': 2, 'B': 1, 'C': 5}, 
1: {'A': 3, 'B': 1, 'C': 2}, 
2: {'A': 1, 'B': 1, 'C': 1}, 
3: {'A': 4, 'B': 2, 'C': 5}
}

所有字典都有相同的键但不同的值。我需要将所有值相加如下。

我尝试使用以下方法合并字典:

new_dict = {}
for k, v in test_dict.items():
    new_dict.setdefault(k, []).append(v) 

我也尝试过使用:

new_dict = {**test_dict[0], **test_dict[1], **test_dict[2], **test_dict[3]}

很遗憾,我没有得到想要的结果。

期望的结果: outcome = {'A': 10, 'B': 5, 'C': 13}

如何将所有值添加到单个字典中?

【问题讨论】:

  • 没有你尝试过的东西?
  • 使用collections.Counter 来简化您的代码。

标签: python python-3.x dictionary


【解决方案1】:

使用pandas的解决方案

将您的dict 转换为pandas.DataFrame,然后对列进行求和并将其转换回dict。

import pandas as pd

df = pd.DataFrame.from_dict(test_dict, orient='index')
print(df.sum().to_dict())

输出:

{'A': 10, 'B': 5, 'C': 13}

替代解决方案

使用collections.Counter,它允许您在dict 中添加相同键的值

from collections import Counter

d = Counter()    
for _,v in test_dict.items():
    d.update(v)

print(d)

【讨论】:

  • @D.Morrissey 欢迎您。我也添加了替代解决方案。希望对您也有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2018-04-16
  • 1970-01-01
  • 2018-10-18
  • 2017-12-17
相关资源
最近更新 更多