Reputation: 19
I am trying to write this program without using Counter.Write a Python program to combine values in python list of dictionaries. Go to the editor Sample data:
[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]
**Expected Output: {'item1': 1150, 'item2': 300}**
So far here's my code.
a=[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]
cp={}
val=0
for d in a:
if d['item'] not in cp:
cp[d['item']]=d['amount']
print(cp)
My output:{'item1': 400, 'item2': 300}
How can I combined the total of of 'item1'?Any help is appreciated?
Upvotes: 0
Views: 943
Reputation: 11520
You can use defaultdict
here.
from collections import defaultdict
for d in l:
data[d['item']] += d['amount']
Out[72]: defaultdict(int, {'item1': 1150, 'item2': 300})
Upvotes: 0
Reputation: 113940
d = {}
for a_dict in all_my_dicts:
for key in a_dict:
d[key] = d.get(key,0)+a_dict[key]
I guess maybe
Upvotes: 0
Reputation: 164623
Here is one way:
from collections import defaultdict
lst = [{'item': 'item1', 'amount': 400},
{'item': 'item2', 'amount': 300},
{'item': 'item1', 'amount': 750}]
d = defaultdict(int)
for i in lst:
d[i['item']] += i['amount']
# defaultdict(<class 'int'>, {'item1': 1150, 'item2': 300})
Upvotes: 2
Reputation: 173
a=[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]
cp={}
val=0
for d in a:
if d['item'] not in cp:
cp[d['item']] = d['amount']
else:
cp[d['item']] += d['amount']
print(cp)
Upvotes: 2