Still have the functional alternatives:
With built-in function map(função, iterável, ...)
apply a function that for each tuple in the form of (chave, valor)
, do the summation of value and return a tuple in format (chave, soma_do_valor)
and convert the mapping result into a dictionary:
times_min = {
'tvmv': [121, 250, 48, 45, 54, 120, 115, 138, 60, 30, 274],
'avic': [358, 60, 40],
'hotels_resorts': [60, 31, 45, 50, 300, 165, 40, 46],
'avani': [70, 40],
'seteais': [164, 115, 78, 54, 45, 17, 180, 220],
'tvpo': [54],
'tlis': [54, 45],
'coimbra': [54],
'oriente': [54],
'tvca': [350, 340, 230, 120, 45]
}
resultado = dict(map(lambda i: (i[0], sum(i[1])), times_min.items()))
print(resultado)
#{'tvmv': 1255, 'avic': 458, 'hotels_resorts': 737, 'avani': 110, 'seteais': 873, 'tvpo': 54, 'tlis': 99, 'coimbra': 54, 'oriente': 54, 'tvca': 1085}
Using the same reasoning with the function starmap()
module itertools. The difference between map()
and starmap()
is that starmap()
already unpacks the iterated item:
from itertools import starmap
times_min = {
'tvmv': [121, 250, 48, 45, 54, 120, 115, 138, 60, 30, 274],
'avic': [358, 60, 40],
'hotels_resorts': [60, 31, 45, 50, 300, 165, 40, 46],
'avani': [70, 40],
'seteais': [164, 115, 78, 54, 45, 17, 180, 220],
'tvpo': [54],
'tlis': [54, 45],
'coimbra': [54],
'oriente': [54],
'tvca': [350, 340, 230, 120, 45]
}
resultado = dict(starmap(lambda k,v: (k, sum(v)), times_min.items()))
print(resultado)
#{'tvmv': 1255, 'avic': 458, 'hotels_resorts': 737, 'avani': 110, 'seteais': 873, 'tvpo': 54, 'tlis': 99, 'coimbra': 54, 'oriente': 54, 'tvca': 1085}
Test the examples in Ideone