neversaint
neversaint

Reputation: 64064

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?

Upvotes: 2

Views: 1381

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

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}

Upvotes: 5

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

Use a dict comprehension and sum, since the values are strings you'll have to convert them to floats first using float.

>>> {k:sum(float(x) for x in v.itervalues()) for k, v in d.iteritems()}
{'Plekhg2': 423.67, 'Barxxxx': 224.12}

For Python 3 use .items() and .values() instead of the .iter(values|items).

Upvotes: 4

EdChum
EdChum

Reputation: 394389

Just for completion in Python 3:

In [134]:

{k:sum(float(x) for x in v.values()) for k, v in my_dict.items()}
Out[134]:
{'Barxxxx': 224.12, 'Plekhg2': 423.67}

Upvotes: 0

Related Questions