I need to create a dictionary that has the sum of elements of another dictionary, in the most computationally efficient way.
The main dictionary is of the form:
{'11': [0.76700000000000002, 3455.0, 0.76700000000000002, 0.76700000000000002, 34.0, 0.76700000000000002], '22': [34.0, 0.76700000000000002]}
I need to create a new dictionary containing the same keys but with the sum of the integers from the first dictionary. The output would then be:
{'11': [3458], '22': [34.767]}
If you want to create a new dictionary (not do the addition on the one you already have) the simplest and most efficient thing to do is to use compression dictionaries together with the built-in function
sum
:In Python 3:
In Python 2:
The output is:
The reason to use
dict.iteritems
in Python 2 is because itdict.items
returns a list of key/value tuples in this version, which can result in memory and efficiency issues with large dictionaries.iteritems
returns an iterator. In Python 3, itdict.items
returns a view object , which is iterable.If you want to avoid precision errors caused by intermediate sums and their floating-point representation as much as possible, you can use
math.fsum
:Python 3:
Python 2:
Departure:
Since you are creating a list with only one element, if you are not going to use that list later, create the keys with the sum only:
Departure:
what you have to do is iterate through the dictionary and on each element iterate through the list and add it
or if you prefer this in a function:
then just call the function:
For more information on the use of dictionaries, I have found some documentation that may be of use to you: