Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum up values from a dictionary (the Python way)

Given the following dictionary, let's call it mydict

 {'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'}, 
  'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }

I want to sum up values for each key from inner dictionary, resulting in:

 {'Plekhg2': 423.67,  # 233.55 + 190.12
  'Barxxxx': 224.12}  # 132.11 + 92.01

How can I achieve that with Python idiom?

like image 476
neversaint Avatar asked Dec 28 '25 10:12

neversaint


1 Answers

With a dict comprehension, using sum() to sum the nested dictionary values; Python 2.6 or before would use dict() and a generator expression:

# Python 2.7
{k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
# Python 3.x
{k: sum(map(float, v.values())) for k, v in mydict.items()}
# Python 2.6 and before
dict((k, sum(float(f) for f in v.values())) for k, v in mydict.iteritems())

You may want to store float values to begin with though.

Demo:

>>> mydict ={'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'}, 
...   'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }
>>> {k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}
{'Plekhg2': 423.67, 'Barxxxx': 224.12}
like image 111
Martijn Pieters Avatar answered Dec 31 '25 00:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!