Home > database >  how to combine (and add) some value of list of dict in Python 3?
how to combine (and add) some value of list of dict in Python 3?

Time:12-03

I have two list of dict :

list_of_dict1 = [{'Coin' : 'AAA', 'Price' : '55'},{'Coin' : 'BBB', 'Price' : '45'}] 

list_of_dict2 = [{'Coin' : 'CCC', 'Price' : '77'},{'Coin' : 'AAA', 'Price' : '45'},{'Coin' : 'DDD', 'Price' : '4'}]

I want a dict (or list of dict) as :

list_of_dict = [{'Coin' : 'AAA', 'Price' : '100'},{'Coin' : 'BBB', 'Price' : '45'},{'Coin' : 'CCC', 'Price' : '77'}]

Can you help me ?

CodePudding user response:

To do this efficiently, use a defaultdict and iterate over each nested entry.

from collections import defaultdict

list_of_dict1 = [{'Coin' : 'AAA', 'Price' : '55'},{'Coin' : 'BBB', 'Price' : '45'}] 
list_of_dict2 = [{'Coin' : 'CCC', 'Price' : '77'},{'Coin' : 'AAA', 'Price' : '45'},{'Coin' : 'DDD', 'Price' : '4'}]

totals = defaultdict(int)
for seq in (list_of_dict1, list_of_dict2):
    for entry in seq:
        totals[entry["Coin"]]  = int(entry["Price"])
list_of_dict = [{"Coin": k, "Price": str(v)} for k, v in totals.items()]

Result:

>>> list_of_dict
[
    {'Coin': 'AAA', 'Price': '100'},
    {'Coin': 'BBB', 'Price': '45'},
    {'Coin': 'CCC', 'Price': '77'},
    {'Coin': 'DDD', 'Price': '4'}
]

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.

  • Related