TIMEX
TIMEX

Reputation: 272304

How do I get the highest key in a python dictionary?

d = {'apple':9,'oranges':3,'grapes':22}

How do I return the largest key/value?

Edit: How do I make a list that has this sorted by largest to lowest value?

Upvotes: 2

Views: 6418

Answers (5)

Thanos Pantos
Thanos Pantos

Reputation: 63

If you want the key with the highest value from your dictionary then this is the answer.

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

Upvotes: 2

John Machin
John Machin

Reputation: 83032

"""How do I print the key, too? """

maxval = max(d.itervalues())
maxkeys = [k for k, v in d.iteritems() if v == maxval]

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600041

max(d.values())

Edited:

The above gives you the max value. To get the key/value pair with the max value, you could do this:

sorted(d.items(), key=lambda x:x[1], reverse=True)[0]

Upvotes: 0

FogleBird
FogleBird

Reputation: 76862

>>> d = {'apple':9,'oranges':3,'grapes':22}
>>> v, k = max((v, k) for k, v in d.items())
>>> k
'grapes'
>>> v
22

Edit: To sort them:

>>> items = sorted(((v, k) for k, v in d.items()), reverse=True)
>>> items
[(22, 'grapes'), (9, 'apple'), (3, 'oranges')]

Upvotes: 11

Jason Webb
Jason Webb

Reputation: 8020

You want to use max(). To get the largest key use:

max(d.keys())

Or:

max(d)

To get the largest value use:

max(d.values())

Upvotes: 2

Related Questions