Add elements contained in a Python dictionary

0

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 that contains the same keys but with the sum of the integers of the first dictionary. The output would then be:

{'11': [3458], '22': [34.767]}
    
asked by Jorge Ponti 18.07.2017 в 16:17
source

2 answers

5

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}

    
answered by 18.07.2017 / 19:31
source
1

what you have to do is go through the dictionary and in each element go through the list and add it

main_dic = {'11': [0.7670, 3455, 0.767, 0.767, 34.0, 0.767], '22': [34.0, 0.767]}
dic_result = {}
for key, value in main_dic.items(): # iterar los item del diccionario
    suma = 0 # variable donde se guardará la suma de los elementos
    for v in value: # iterar los elementos
        suma += v # sumar los elementos y guardarlos
    dic_result[key] = suma # añadir al nuevo diccionario la misma llave con la suma de los elementos

or if you prefer this in a function:

    def suma_valores_dic(main_dic):
        dic_result = {}
        for key, value in main_dic.items():
            suma = 0
            for v in value:
                suma += v
            dic_result[key] = suma
        return dic_result

then it's just call the function:

diccionario = {'11': [0.7670, 3455, 0.767, 0.767, 34.0, 0.767], '22': [34.0, 0.767]}
resultado = suma_valores_dic(diccionario)
print(resultado)

for more information on the use of the dictionaries I found some documentation that can help you:

  • link
  • link especially in booksweb , there is a lot of information that can help you. Also your session of Python for beginners
  • answered by 18.07.2017 в 18:43