Add values for keys that contains similar string in python

Question:

I have dict as

values={'P-ETH-900':Decimal(122),'P-ETH-700':Decimal(455),'P-BTC-900':Decimal(12),'P-BTC-700':Decimal(55)}

I want to add the decimals that has condition like

eth=Decimal(0)
for i,j in values.items():
   if 'ETH' in i:
      eth=eth+j

So basically, for each similar items , need to sum up the decimal values.

output:

{'ETH':'577','BTC':'67'}
Asked By: Madan

||

Answers:

Use a dictionary comprehension that calls sum():

result = {currency: sum(v for k, v in values.items() if currency in k) for currency in ['ETH', 'BTC']}

Or you can use a defaultdict to extract the currency from the keys, assuming it’s always the second component.

from collections import defaultdict

result = defaultdict(int)

for key, value in values.items():
    result[key.split('-')[1]] += value
Answered By: Barmar