Skip to content

Sorted Dictionary in Python: A Simple Guide

CodeMDD.io

Sorting a Python Dictionary: Values, Keys, and More

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries in Python were unordered. However, starting from Python 3.6, dictionaries preserve the insertion order of their elements. From Python 3.7 onwards, the order of elements in a dictionary is guaranteed.

Understanding What Sorting A Dictionary Really Means

When we talk about sorting a dictionary, it means sorting the key-value pairs based on either the keys or the values.

Sorting Dictionaries in Python

Using the sorted() Function

To sort a dictionary, you can use the built-in sorted() function. However, keep in mind that the sorted() function returns a list of the dictionary’s keys.

fruits = {'apple': 3, 'banana': 2, 'orange': 4}
sorted_fruits = sorted(fruits)

The sorted_fruits list will contain the sorted keys of the fruits dictionary: ['apple', 'banana', 'orange'].

Getting Keys, Values, or Both From a Dictionary

Python provides several methods to access the keys, values, or both from a dictionary:

  • Use the keys() method to get a dictionary view object containing the keys.
  • Use the values() method to get a dictionary view object containing the values.
  • Use the items() method to get a dictionary view object containing the key-value pairs.
fruits = {'apple': 3, 'banana': 2, 'orange': 4}
# Get the keys
fruit_keys = fruits.keys() # dict_keys(['apple', 'banana', 'orange'])
# Get the values
fruit_values = fruits.values() # dict_values([3, 2, 4])
# Get the key-value pairs
fruit_items = fruits.items() # dict_items([('apple', 3), ('banana', 2), ('orange', 4)])

Understanding How Python Sorts Tuples

When sorting a dictionary based on values or keys, Python actually sorts a list of tuples. Each tuple contains a key-value pair from the dictionary. During sorting, Python compares the tuples based on the first elements (keys) by default. If there is a tie, it compares the second elements (values), and so on.

fruits = {'apple': 3, 'banana': 2, 'orange': 4}
sorted_fruits = sorted(fruits.items())
# Output: [('apple', 3), ('banana', 2), ('orange', 4)]

Using the key Parameter and Lambda Functions

You can customize the sorting behavior by using the key parameter of the sorted() function. This parameter allows you to specify a function that will be used to extract a comparison key from each tuple.

fruits = {'apple': 3, 'banana': 2, 'orange': 4}
# Sort by values in increasing order
sorted_fruits = sorted(fruits.items(), key=lambda x: x[1])
# Output: [('banana', 2), ('apple', 3), ('orange', 4)]

Selecting a Nested Value With a Sort Key

If you have a dictionary with nested values and want to sort based on a particular nested attribute, you can use a sort key that accesses the nested attribute.

contacts = {
'Alice': {'email': 'alice@example.com', 'age': 25},
'Bob': {'email': 'bob@example.com', 'age': 30},
'Charlie': {'email': 'charlie@example.com', 'age': 20}
}
# Sort by age in increasing order
sorted_contacts = sorted(contacts.items(), key=lambda x: x[1]['age'])
# Output: [('Charlie', {'email': 'charlie@example.com', 'age': 20}), ('Alice', {'email': 'alice@example.com', 'age': 25}), ('Bob', {'email': 'bob@example.com', 'age': 30})]

Converting Back to a Dictionary

If you want to convert the sorted list of key-value pairs back to a dictionary, you can use the dict() constructor.

fruits = {'apple': 3, 'banana': 2, 'orange': 4}
sorted_fruits = sorted(fruits.items())
# Convert back to a dictionary
sorted_fruits_dict = dict(sorted_fruits)
# Output: {'apple': 3, 'banana': 2, 'orange': 4}

Considering Strategic and Performance Issues

Using Special Getter Functions to Increase Performance and Readability

If you need to perform multiple sorting operations on a dictionary, using special getter functions like itemgetter() from the operator module can improve the performance and readability of your code.

from operator import itemgetter
fruits = {'apple': 3, 'banana': 2, 'orange': 4}
# Sort by values in increasing order using itemgetter()
sorted_fruits = sorted(fruits.items(), key=itemgetter(1))
# Output: [('banana', 2), ('apple', 3), ('orange', 4)]

Measuring Performance When Using itemgetter()

To measure the performance of different sorting techniques, you can use the timeit module. This module allows you to measure the execution time of your code.

import timeit
fruits = {'apple': 3, 'banana': 2, 'orange': 4}
# Time the execution of sorting using itemgetter()
time_taken = timeit.timeit(lambda: sorted(fruits.items(), key=itemgetter(1)))
# Output: Time taken for sorting: <execution time>
print('Time taken for sorting:', time_taken)

Judging Whether You Want to Use a Sorted Dictionary

Although you can sort a dictionary in Python, it’s worth considering whether a sorted dictionary is the best data structure for your use case. Depending on your requirements, other data structures like lists or sets might be more suitable.

Comparing the Performance of Different Data Structures

To compare the performance of different data structures, you can measure the execution time of common operations using the timeit module.

import timeit
# Time the execution of adding elements to a list, set, and dictionary
time_taken_list = timeit.timeit('my_list.append(1)', setup='my_list = []', number=1000000)
time_taken_set = timeit.timeit('my_set.add(1)', setup='my_set = set()', number=1000000)
time_taken_dict = timeit.timeit('my_dict[1] = None', setup='my_dict = {}', number=1000000)
# Output: Time taken for list: <execution time>
# Time taken for set: <execution time>
# Time taken for dictionary: <execution time>
print('Time taken for list:', time_taken_list)
print('Time taken for set:', time_taken_set)
print('Time taken for dictionary:', time_taken_dict)

Comparing the Performance of Sorting

You can also measure the performance of different sorting techniques by timing their execution.

import timeit
fruits = {'apple': 3, 'banana': 2, 'orange': 4}
# Time the execution of sorting using sorted() and itemgetter()
time_taken_sorted = timeit.timeit(lambda: sorted(fruits.items(), key=lambda x: x[1]))
time_taken_itemgetter = timeit.timeit(lambda: sorted(fruits.items(), key=itemgetter(1)))
# Output: Time taken for sorting using sorted(): <execution time>
# Time taken for sorting using itemgetter(): <execution time>
print('Time taken for sorting using sorted():', time_taken_sorted)
print('Time taken for sorting using itemgetter():', time_taken_itemgetter)

Comparing the Performance of Lookups

To compare the performance of lookup operations in different data structures, you can use the timeit module.

import timeit
# Time the execution of looking up an element in a list, set, and dictionary
time_taken_list_lookup = timeit.timeit('1 in my_list', setup='my_list = [1, 2, 3]', number=1000000)
time_taken_set_lookup = timeit.timeit('1 in my_set', setup='my_set = {1, 2, 3}', number=1000000)
time_taken_dict_lookup = timeit.timeit('1 in my_dict', setup='my_dict = {1: None, 2: None, 3: None}', number=1000000)
# Output: Time taken for list lookup: <execution time>
# Time taken for set lookup: <execution time>
# Time taken for dictionary lookup: <execution time>
print('Time taken for list lookup:', time_taken_list_lookup)
print('Time taken for set lookup:', time_taken_set_lookup)
print('Time taken for dictionary lookup:', time_taken_dict_lookup)

Conclusion

In this tutorial, you learned how to sort a dictionary in Python. You explored different sorting techniques using the sorted() function, the key parameter, and lambda functions. You also considered strategic and performance issues when working with sorted dictionaries. By understanding the different methods and their performance implications, you can choose the most suitable approach for your specific use case.