logo
Python Data Structures - Interview Questions and Answers
How do you sort a dictionary by keys and values?

Sorting a dictionary in Python can be done in two ways:

  1. Sorting by Keys
  2. Sorting by Values

Since dictionaries are unordered before Python 3.7, sorting creates a new dictionary with a specific order.


1. Sorting a Dictionary by Keys
  • Use the sorted() function on dict.keys() and reconstruct the dictionary.
Example :
my_dict = {"b": 2, "a": 1, "c": 3}

# Sorting by keys (ascending order)
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

* Default sorting is in ascending order (A → Z, 0 → 9).
* Use reverse=True for descending order.


2. Sorting a Dictionary by Values
  • Sort based on the second element in (key, value) pairs.
Example :
my_dict = {"b": 2, "a": 1, "c": 3}

# Sorting by values (ascending order)
sorted_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_by_values)  # Output: {'a': 1, 'b': 2, 'c': 3}

* Sorting is based on values instead of keys.
* Use reverse=True for descending order.


3. Sorting by Keys in Descending Order
sorted_dict_desc = dict(sorted(my_dict.items(), reverse=True))
print(sorted_dict_desc)  # Output: {'c': 3, 'b': 2, 'a': 1}

4. Sorting by Values in Descending Order
sorted_by_values_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_by_values_desc)  # Output: {'c': 3, 'b': 2, 'a': 1}

Which Method Should You Use?
Sorting Criteria Code
Sort by Keys (Ascending) dict(sorted(my_dict.items()))
Sort by Keys (Descending) dict(sorted(my_dict.items(), reverse=True))
Sort by Values (Ascending) dict(sorted(my_dict.items(), key=lambda item: item[1]))
Sort by Values (Descending) dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))