Alejandro
Alejandro

Reputation: 5226

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,

Upvotes: 2

Views: 4172

Answers (3)

Calvin
Calvin

Reputation: 11

max(d.values()) will give the largest value in the dictionary d

Upvotes: 1

arshajii
arshajii

Reputation: 129507

You could just use max(d.keys()) or equivalently simply max(d) (this is the better alternative).

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304167

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

Upvotes: 11

Related Questions