简体   繁体   中英

getting value of the maximum key in dictionary (python)

I only found here how can I get the key of the maximum value:

max(d, key=d.get())

but I need to search the maximum key and return the value of this key.

thanks,

To get the maximum key

max(d)

And for the value, just look it up in the dictionary

d[max(d)]

Note: You can also use max(d.keys()) , but it a bit slower because it needs to build a temporary list

$ python -m timeit -s 'd={x:str(x) for x in range(10000)}' 'max(d)'
1000 loops, best of 3: 377 usec per loop
$ python -m timeit -s 'd={x:str(x) for x in range(10000)}' 'max(d.keys())'
1000 loops, best of 3: 476 usec per loop

您可以使用max(d.keys())或等效max(d) (这是更好的选择)。

max(d.values())将给出字典d中的最大值

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