I have two list of dict :
JavaScript
x
4
1
list_of_dict1 = [{'Coin' : 'AAA', 'Price' : '55'},{'Coin' : 'BBB', 'Price' : '45'}]
2
3
list_of_dict2 = [{'Coin' : 'CCC', 'Price' : '77'},{'Coin' : 'AAA', 'Price' : '45'},{'Coin' : 'DDD', 'Price' : '4'}]
4
I want a dict (or list of dict) as :
JavaScript
1
2
1
list_of_dict = [{'Coin' : 'AAA', 'Price' : '100'},{'Coin' : 'BBB', 'Price' : '45'},{'Coin' : 'CCC', 'Price' : '77'}]
2
Can you help me ?
Advertisement
Answer
To do this efficiently, use a defaultdict
and iterate over each nested entry.
JavaScript
1
11
11
1
from collections import defaultdict
2
3
list_of_dict1 = [{'Coin' : 'AAA', 'Price' : '55'},{'Coin' : 'BBB', 'Price' : '45'}]
4
list_of_dict2 = [{'Coin' : 'CCC', 'Price' : '77'},{'Coin' : 'AAA', 'Price' : '45'},{'Coin' : 'DDD', 'Price' : '4'}]
5
6
totals = defaultdict(int)
7
for seq in (list_of_dict1, list_of_dict2):
8
for entry in seq:
9
totals[entry["Coin"]] += int(entry["Price"])
10
list_of_dict = [{"Coin": k, "Price": str(v)} for k, v in totals.items()]
11
Result:
JavaScript
1
8
1
>>> list_of_dict
2
[
3
{'Coin': 'AAA', 'Price': '100'},
4
{'Coin': 'BBB', 'Price': '45'},
5
{'Coin': 'CCC', 'Price': '77'},
6
{'Coin': 'DDD', 'Price': '4'}
7
]
8
Note: it looks like {'Coin': 'DDD', 'Price': '4'}
is excluded from your result and is unclear why. If that is intentional and you want something like only entries that are members of both lists, you would want to keep a counter and weed out those entries that do not have a total count equal to the number of lists.