简体   繁体   中英

How to give the max item of a dictionary given a value somewhere in an array in the value?

In python, say I have a dictionary

{1:[1,333], 2:[5,22], 3:[8:0]}

I want to return the max item in the dictionary by the second item in the value array, so in this case, 333 beats all the rest numbers in the same place, I wish the function can return

(1,[1,33])

Is there any neat way to implement this using max() with key or something else?

>>> d = {1:[1,333], 2:[5,22], 3:[8, 0]}
>>> max(d.items(), key=lambda e: e[1][1])
(1, [1, 333])

You can achieve this using the key argument to max() , ie:

d = {1:[1,333], 2:[5,22], 3:[8,0]}
# Use d[k][1] so that max is based on the second
#   item in each list
max_key = max(d, key=lambda k: d[k][1])
print((max_key, d[max_key]))
(1, [1, 333])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM