因此,如果我想找到相同的键并将这些值加到字典列表中。
如果我找到键名“ hi”, [{'hello':10,'hi':2},{'hi':3}]
将返回5
答案 0 :(得分:0)
sum
和列表理解可以很容易地解决这个问题。
x = [{'hello': 10, 'hi': 2}, {'hi': 3}, {'nohihere': 8}]
all_hi = sum(d.get('hi', 0) for d in x)
print(all_hi)
5
答案 1 :(得分:0)
您可以尝试以下方法:
dlist = [{'hello':10,'hi':2},{'hi':3}]
sum(map(lambda x: x.get('hi',0), dlist))
答案 2 :(得分:-1)
您只需要检查每个对象是否具有带有“ hi”的键
list = [{'hello':10,'hi':2},{'hi':3},{'nothi':4}]
sum = 0
for i in list:
if 'hi' in i:
sum += i['hi']
print(sum)
答案 3 :(得分:-1)
这是另一种解决方案
my_dict = [{'hello':10,'hi':2},{'hi':3}]
common_keys = set.intersection(*map(set, my_dict))
summed_dict = {key: sum(d[key] for d in my_dict) for key in common_keys}
print(summed_dict)
o / p-{'hi': 5}
否则您可以使用此
import functools as ft
my_dict = [{'hello':10,'hi':2},{'hi':3}]
print({k: sum(d[k] for d in my_dict) for k in ft.reduce(set.intersection, map(set, my_dict))})
o / p-{'hi': 5}