Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
TIMEX Avatar asked Mar 23 '26 04:03

TIMEX


1 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')]
like image 196
FogleBird Avatar answered Mar 24 '26 18:03

FogleBird