2

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.

0

2 Answers 2

7

Possibly a more pythonic alternative:

>>> max(pets, key=pets.get)
'Cat'
1
  • Wow, that's a much neater method. Thank you! Nov 23, 2014 at 15:42
0
sorted_pets[0][0]

Try this.This should do it.

1
  • Thank you! How did I miss that?! So simple! Nov 23, 2014 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.