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 create a list sorted by largest to lowest value?

+2


a source to share


4 answers


>>> 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')]

      

+10


a source


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

max(d.keys())

      

Or:



max(d)

      

To get the highest value:

max(d.values())

      

+2


a source


max(d.values())

      

Edited:

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

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

      

0


a source


"" How to print the key too? "" "

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

      

0


a source







All Articles