If you want to create a new dictionary (do not do the addition on the one you already have) the simplest and most efficient way is to use dictionaries by compression next to the pre-built function sum
:
d = {'11': [0.76700000000000002, 3455.0, 0.76700000000000002,
0.76700000000000002, 34.0, 0.76700000000000002],
'22': [34.0, 0.76700000000000002]}
-
In Python 3:
r = {key: [sum(value)] for key, value in d.items()}
-
In Python 2:
r = {key: [sum(value)] for key, value in d.iteritems()}
The output is:
{'11': [3492.0679999999993], '22': [34.767]}
The reason for using dict.iteritems
in Python 2 is because dict.items
returns a list of key / value tuples in this version, which may result in a memory and efficiency problem with extensive dictionaries. iteritems
returns an iterator. In Python 3, dict.items
returns a view object , which is iterable.
If you want to avoid as much as possible the precision errors caused by the intermediate sums and their floating-point representation, you can use math.fsum
:
-
Python 3:
import math
r = {key: [math.fsum(value)] for key, value in d.items()}
-
Python 2:
import math
r = {key: [math.fsum(value)] for key, value in d.iteritems()}
Exit:
{'11': [3492.068], '22': [34.767]}
Since you are creating a list with a single element, if you are not going to use that list later, create the keys with the addition only:
r = {key: math.fsum(value) for key, value in d.items()}
Exit:
{'11': 3492.068, '22': 34.767}