Haoyu Haoyu -4 years ago 102
Python Question

Get key of biggest-sum list in a Dictionary of Lists

I have a dictionary with keys of integers and values of lists.

dict = {1: [0.1, 0.4, 0.05, 0.25], 3: [1, 8, 0.2, 3], 29: [2, 0, 1, 7]}


I want to get

largest_k = 3 # as its list sums to 12.2


I have tried

for n in dict.keys():
d[n] = sum(dict[n])
largest_k = max(d, key=d.get)


And I get

d = {1: 0.8, 3: 12.2, 29: 10}
largest_k = 3


as intended but it's cumbersome (and creates a new dictionary).

How do I find largest_k without resorting to a new dictionary or modifying the original dictionary?

Answer Source

Use a more detailed sorting key, and try the max function instead (since you only want the largest one):

>>> dct = {1: [0.1, 0.4, 0.05, 0.25], 3: [1, 8, 0.2, 3], 29: [2, 0, 1, 7]}
>>> max(dct.items(), key=lambda x: sum(x[1]))[0]
3

And don't use dict as a name, as it's already in use by the dict built-in function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download