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?
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}
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)
.
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}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.