计算嵌套Python字典中的列的总和



我有一个字典,格式如下:

{
'1000': {
'owner_id':'1000',
'in_hours':100,
'us_hours':200,
'total_revenue':100
},
'1084': {
'owner_id':'10084',
'in_hours':100,
'us_hours':200,
'total_revenue':100
}
}

现在我需要如下的总和:

{
'in_hours':200,
'us_hours':400,
'total_revenue':200
}

如何做到这一点?我知道我可以在循环中完成这项工作,但我有很多键,我不想单独指定所有键。

实现这一点的方法取决于如何确定哪些值是相关的。让我们假设您想要对所有为整数的值求和。通过这种方式,我们不需要知道密钥是什么,只需要知道它们的值。

data = {
'1000': {
'owner_id':'1000',
'in_hours':100,
'us_hours':200,
'total_revenue':100
},
'1084': {
'owner_id':'10084',
'in_hours':100,
'us_hours':200,
'total_revenue':100
}
}
result = {}
for v in data.values():
assert isinstance(v, dict)
for k, v in v.items():
if isinstance(v, int):
result[k] = result.get(k, 0) + v
print(result)

输出:

{'in_hours': 200, 'us_hours': 400, 'total_revenue': 200}

如果您知道密钥以key前缀开头,您可以执行以下操作:

from collections import defaultdict
result = defaultdict(int)
for v in data.values():
for key, value in v.items():
if key.startswith('key'):
result[key] += value
print(dict(result))

输出:

{
'key1': 200, 
'key2': 400, 
'key3': 200
}

您可以使用采集接口

collections.Counter()    
for d in data.values():
counter.update(d)
result = dict(counter)

output 
{'key3': 200, 'key2': 400, 'key1': 200, 'owner_id': '100841000'}

使用collections.defaultdict并将内部字典的所有值相加,这些值是数字(intfloat((因此您不需要知道名称(。我想你不想连接字符串ID(无论如何,这似乎是多余的,因为它们已经是外部字典的密钥了?(:

from collections import defaultdict
in_dict = {
'1000': {
'owner_id': '1000',
'key1': 100,
'key2': 200,
'key3': 100,
'time': 0.7
},
'1084': {
'owner_id': '1084',
'key1': 100,
'key2': 200,
'key3': 100,
'time': 4.5
}
}
out_dict = defaultdict(int)
for outer in in_dict.values():
for key, value in outer.items():
if isinstance(value, (int, float)):
out_dict[key] += value
print(out_dict)
# defaultdict(<class 'int'>, {'key1': 200, 'key2': 400, 'key3': 200, 'time': 5.2})

具有tryexcept的版本也是可能的,因此我们不专门针对intfloat:

out_dict = defaultdict(int)
for outer in in_dict.values():
for key, value in outer.items():
try:
out_dict[key] += value
except TypeError:
# need to remove key due to side effects of defaultdict
del out_dict[key]
print(out_dict)
# defaultdict(<class 'int'>, {'key1': 200, 'key2': 400, 'key3': 200, 'time': 5.2})

最新更新