Redeem dictionary key with maximum sum of respective value

6

I have the following dictionary:

dic = {'bsx_8612': [23, 567, 632], 'asd_6375': [654, 12, 962], 'asd_2498': [56, 12, 574], 'bsx_9344': [96, 1022, 324]}

I want to retrieve the key whose value has the largest sum of its elements. How I am doing:

chaves, valores = [], []
for item in dic:
    valores.append(sum(dic.get(item)))
    chaves.append(item)

chave = chaves[valores.index(max(valores))]
print(chave)
>>> asd_6375

Is there a more practical way to do this?

    
asked by anonymous 24.06.2015 / 17:19

1 answer

5
dic = {'bsx_8612': [23, 567, 632], 'asd_6375': [654, 12, 962], 'asd_2498': [56, 12, 574], 'bsx_9344': [96, 1022, 324]}

print max(dic.iteritems(), key = lambda (k, v): sum(v))[0]

# Python 3
print(max(dic.items(), key = lambda t: sum(t[1]))[0])

In the functions sort , sorted , max , min , ... you can pass the key = … parameter to use a function of your data as a comparison / sort key.

Ideone .

    
24.06.2015 / 17:25