Oceanescence
Oceanescence

Reputation: 2127

Sorting a dictionary and outputting the key which corresponds to the highest value?

I am trying to output the name of the pet which corresponds to the highest value:

import operator
pets = {"Dog":3, "Cat":5, "Rabbit":0}
sorted_pets = sorted(pets.items(), key=operator.itemgetter(1), reverse = True)
print (sorted_pets[0])

The code above outputs ['Cat', 5]. How can I change it so it just outputs Cat?

Thanks.

Upvotes: 2

Views: 76

Answers (2)

wim
wim

Reputation: 362478

Possibly a more pythonic alternative:

>>> max(pets, key=pets.get)
'Cat'

Upvotes: 7

vks
vks

Reputation: 67968

sorted_pets[0][0]

Try this.This should do it.

Upvotes: 0

Related Questions