I have a list of dictionary:
data = [
{"2010" : {'A' : 2,'B' : 3,'C' : 5,}},
{"2011" : {'A' : 1,'B' : 2,}},
{"2010" : {'A' : 1,'B' : 2,}}
]
I'd like sum the values where the key is same. So the result I expected should be like this:
res =
{"2010" : {'A' : 3, 'B' : 5, 'C' : 5},
"2011" : {'A' : 1, 'B' : 2}}
How can I do this easily?
CodePudding user response:
So you have a list of dictionaries as input and you want to create an output dictionary which contains the sums:
from collections import defaultdict
data = [{'2010': {'A': 2, 'B': 3, 'C': 5}}, {'2011': {'A': 1, 'B': 2}}, {'2010': {'A': 1, 'B': 2}}]
def sum_values(data):
out = {}
for i in data:
for k in i.keys():
if k not in out:
out[k] = defaultdict(int)
for k1,v1 in i[k].items():
out[k][k1] = v1
return out
sum_values(data)
{'2010': defaultdict(<class 'int'>, {'A': 3, 'B': 5, 'C': 5}), '2011': defaultdict(<class 'int'>, {'A': 1, 'B': 2})}
CodePudding user response:
Try this
data = [
{ "2010":{'A':2,'B':3,'C':5,}},
{ "2011":{'A':1,'B':2,}},
{"2010":{'A':1,'B':2,}}
]
res = {}
for d in data:
# print(d.items())
items = list(d.items())[0] # convert to list because dict items isn't subscriptable
year, value = items
if year not in res:
res[year] = value
res
is equal to
{
'2010': {'A': 2, 'B': 3, 'C': 5},
'2011': {'A': 1, 'B': 2}
}
CodePudding user response:
you can use .get()
like below.
Try this:
data = [
{"2010" : {'A' : 2,'B' : 3,'C' : 5,}},
{"2011" : {'A' : 1,'B' : 2,}},
{"2010" : {'A' : 1,'B' : 2,}}
]
dct = {}
for d in data:
for k,v in d.items():
dct[k] = dct.get(k,{})
for k2,v2 in v.items():
dct[k][k2] = dct[k].get(k2,0) v2
print(dct)
Otput:
{'2010': {'A': 3, 'B': 5, 'C': 5}, '2011': {'A': 1, 'B': 2}}