0

I have this dictionary:

    a_dict = {"car":5,"laptop":17,"telephone":3,"photo":14}

I would like to print the key which has the highest value. For example, I would like to print out the key laptop because it has the highest number

I have tried this so far:

    def get_oldest(things):
        new_list = []
        for elements in things:
            new_list.append(things[element])
            new_list.sort()    

Now, I have sorted the list from the smallest to the highest, so I know that the last item in the list has the highest value, but how do I match that to the correct key and print that.

lionking-123
  • 301
  • 3
  • 12
karl johan
  • 13
  • 1

1 Answers1

2

There is a much easier way:

a_dict = {"car": 5,"laptop": 17,"telephone": 3,"photo": 14}
oldest = max(a_dict, key=a_dict.get)
# "laptop"

This uses max with a key function. You can use max on the plain dict because iterating a dict produces its keys.

user2390182
  • 72,016
  • 6
  • 67
  • 89