Redeem dictionary key with maximum sum of respective value

Asked

Viewed 922 times

7

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 redeem the key whose value has the highest 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

There is a more practical way to do this operation?

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 office sort, sorted, max, min, ... you can pass the parameter key = … to use a function of your data as a comparison/sorting key.

Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.