Skip to content

Instantly share code, notes, and snippets.

@pford68
Last active March 5, 2026 23:42
Show Gist options
  • Select an option

  • Save pford68/30a8fe396c6fc1fa00fc3572f7020125 to your computer and use it in GitHub Desktop.

Select an option

Save pford68/30a8fe396c6fc1fa00fc3572f7020125 to your computer and use it in GitHub Desktop.
Sorting a dictionary by value in Python #python #sorting

Below we sort a dictionary, then find the key with the highest value.

d = {'a': 10, 'b': 20, 'c': 30}
sorted_items = sorted(d.items(), key=lambda item: item[1])
print(sorted_items[-1][0])
  1. Get items() from the dictionary.
  2. Pass the to sorted and pass a lambda to in key parameter. This tells the sorted() function whhat to sort on.
  3. Get the last entry in the sorted list of entries.
  4. In this case, since we want the key for the kighest value, get the first item from the tuple in the first entiy in the sorted items.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment