Reputation: 762
I have two list with dictionaries:
rich = [
{'currency': 'USD', 'value': 100},
{'currency': 'EUR', 'value': 110},
{'currency': 'USD', 'value': 120},
{'currency': 'GBP', 'value': 130},
]
poor = [
{'currency': 'USD', 'value': 10},
{'currency': 'AED', 'value': 20},
]
how can I combine both so that I can get:
rich_and_poor = [
{'currency': 'USD', 'value': 110}, # +10
{'currency': 'EUR', 'value': 110},
{'currency': 'GBP', 'value': 130},
{'currency': 'AED', 'value': 20} # new dictionary
]
?
The
from collections import Counter
is useful, because it can sum dictionaries values with same key, but I still can't figure out how to do it with list of dictionairies.
x = {'value': 123}
y = {'value': 2}
Counter(x) + Counter(y) = {'value': 125}
Upvotes: 0
Views: 1109
Reputation: 31260
A more logical structure for this would be to have one dictionary, with currencies as keys and values as values. Let's use a defaultdict to create one (so that new keys start out as 0 automatically):
currencies = defaultdict(int)
Now add your dicts to it:
for currencydict in rich + poor:
currencies[currencydict['currency']] += currencydict['value']
That yielded something like (not necessarily the same order):
{
'USD': 230,
'EUR': 110,
'GBP': 130,
'AED': 20
}
And now, if you really have to, convert it back to a list like yours:
rich_and_poor = [{'currency': key, 'value': value} for key, value in currencies.items()]
Upvotes: 1