Python
Container Types
dict
sort

Sorting a Python dictionary: explanation and examples

Python dictionaries are useful data structures that store data as key-value pairs.

However, dictionaries are not ordered by default, and sometimes you need to sort the data in a dictionary in a particular order.

In this article, we'll look at how to sort a Python dictionary. Here are the specifics.

  1. sort by key
  2. sort by value (lambda function)
  3. sort by multiple values or in descending order
  4. sort multiple dictionaries
  5. sort a dictionary within a Python list
  6. sort dictionary output

1. Sort by key

To sort a dictionary by its key, you can use the built-in function sorted().

When you sort a dictionary by key, the order by key is guaranteed and the result is easy to predict. Because keys uniquely identify each key-value pair, sorting by them can help you quickly navigate through a dictionary or find the information you need.

dictionary = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = dict(sorted(dictionary.items()))
print(sorted_dict)
 
# Output
{'a': 1, 'b': 2, 'c': 3}

2. Sorting by value (lambda function)

To sort a dictionary by value, use the lambda function in the key argument of the sorted() function to sort the dictionary by value.

Sorting a dictionary by value ensures order by value, which makes it easier to see distributions or patterns in the values.

The lambda function makes it easy to set up a qualifying condition based on value. The lambda function is an anonymous function, which is useful for implementing simple functions.

dictionary = {'a': 3, 'b': 1, 'c': 2}
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1]))
print(sorted_dict)
 
# Output
{'b': 1, 'c': 2, 'a': 3}

3. Sort multiple values or in descending order

3.1. Sorting by multiple values

When a dictionary has multiple values, sorting the dictionary by them is a bit more complicated, especially when the values are ordered data types like tuples or lists.

For example, let's say you have a dictionary with keys and values as shown below.

dict_to_sort = {'a': (2, 3), 'b': (1, 3), 'c': (1, 2), 'd': (2, 2)}

Here, the value is a tuple with two elements. To sort it by key and first element, then second element, you could write code like this

sorted_dict = dict(sorted(dict_to_sort.items(), key=lambda item: (item[0], item[1][0], item[1][1])))
 
print(sorted_dict)
 
# Output
{'b': (1, 3), 'c': (1, 2), 'a': (2, 3), 'd': (2, 2)}

The key=lambda item: (item[0], item[1][0], item[1][1]) part is the code that specifies the sort key.

Here, item[0] represents the key of the dictionary, item[1][0] represents the first element of the tuple that is the value of the dictionary, and item[1][1] represents the second element of the tuple that is the value of the dictionary.

So this code sorts the dictionary by key, then by the first element of the tuple, then by the second element.

In this way, you can sort a dictionary by multiple values, using each element that makes up the value of the dictionary as the basis for sorting.

3.2. Sorting in descending order

To sort a dictionary in descending order, you can set the reverse argument of the sorted() function to True.

For example, suppose you have a dictionary like the one below.

my_dict = {'b': 5, 'a': 9, 'c': 7}

To sort this dictionary in descending order by key, you can do the following

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[0], reverse=True))
 
print(sorted_dict)
 
# Output
{'c': 7, 'b': 5, 'a': 9}

Similarly, to sort this dictionary by value in descending order, you could do the following

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
 
print(sorted_dict)
 
# Output
{'a': 9, 'c': 7, 'b': 5}

where key=lambda item: item[0] or key=lambda item: item[1] is code that specifies the sorting criteria, reverse=True tells the dictionary to sort in descending order by this criterion.

4. Sorting multiple dictionaries

When a dictionary has another dictionary inside it, it is called a "nested dictionary". Nested dictionaries are useful for structuring data hierarchically, and are often seen in data formats such as JSON.

However, sorting nested dictionaries can be a bit tricky. You need to sort by a key in the outer dictionary, or by a key or value in the inner dictionary.

For example, let's say you have a nested dictionary with "username" as a key and a dictionary with "age" and "address" as values, as shown below.

nested_dict = {'John': {'age': 25, 'address': '123 St'},
                'Jane': {'age': 23, 'address': '456 St'},
                'Dave': {'age': 30, 'address': '789 St'}}

To sort this nested dictionary by "age", you could write code like this

sorted_dict = dict(sorted(nested_dict.items(), key=lambda item: item[1]['age']))
print(sorted_dict)
 
# Output
{'Jane': {'age': 23, 'address': '456 St'},
'John': {'age': 25, 'address': '123 St'},
'Dave': {'age': 30, 'address': '789 St'}}

The key=lambda item: item[1]['age'] part is the code that specifies the sort key to perform the sort by 'age'. In this case, item[1] represents the value of a dictionary, which is another dictionary.

So item[1]['age'] would be code to get the value for 'age' from a nested dictionary.

By organizing your nested dictionaries in this way, you can easily understand and manage your data according to each level. Of course, the deeper the nesting level, the more complicated the sorting will be, but the same principle applies.

5. Sorting a Dictionary in a Python List

To sort a dictionary within a list, specify the key of the dictionary you want to sort on in the key argument.

list_of_dict = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 23}, {'name': 'Dave', 'age': 30}]
sorted_list_of_dict = sorted(list_of_dict, key=lambda d: d['age'])
 
print(sorted_list_of_dict)
 
# Output
[{'name': 'Jane', 'age': 23}, {'name': 'John', 'age': 25}, {'name': 'Dave', 'age': 30}]

6. Sorted dictionary output

To sort and output a dictionary, use a for statement to iterate over key-value pairs.

dictionary = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = dict(sorted(dictionary.items()))
 
for key, value in sorted_dict.items():
    print(f"{key}: {value}")
 
# Output
a: 1
b: 2
c: 3

Conclusion

So far we've covered six topics related to sorting Python dictionaries. Hopefully these will help you in your real-world work in the future.

copyright for Sorting a Python dictionary: explanation and examples

© 2023 All rights reserved.