5 Best Ways to Convert Python Dict to Sorted List

πŸ’‘ Problem Formulation: Converting a dictionary to a sorted list in Python is a common task that requires transforming the key-value pairs into list elements while ensuring they’re ordered. For example, given a dictionary {'apple': 2, 'banana': 3, 'cherry': 1}, the desired output might be a list of tuples sorted by item or count like [('cherry', 1), ('apple', 2), ('banana', 3)].

Method 1: Using the sorted() Function and a Lambda Expression

This method involves the use of the built-in sorted() function, coupled with a lambda function to specify the dictionary keys or values as the sort key. This function is versatile, allowing for both ascending and descending sort orders.

Here’s an example:

my_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
sorted_list = sorted(my_dict.items(), key=lambda item: item[1])
print(sorted_list)

Output: [('cherry', 1), ('apple', 2), ('banana', 3)]

This code uses my_dict.items() to get a view object of the dictionary’s key-value pairs, then sorts them with sorted() by the second element of each tuple (the values) using a lambda function as the key.

Method 2: Using the operator Module

The operator module provides functions that correspond to intrinsic operations of Python. For sorting dictionaries, operator.itemgetter() can be particularly useful, offering more speed and readability than a lambda function.

Here’s an example:

import operator
my_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
sorted_list = sorted(my_dict.items(), key=operator.itemgetter(1))
print(sorted_list)

Output: [('cherry', 1), ('apple', 2), ('banana', 3)]

With operator.itemgetter(1), we’re specifying that the values (second item in each key-value tuple) should be used for sorting purposes.

Method 3: Dictionary Comprehension and sort()

For those preferring a more traditional approach, a dictionary comprehension can format and prepare the data, followed by the use of the list method sort() to sort the list in place.

Here’s an example:

my_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
sorted_list = [(k, v) for k, v in my_dict.items()]
sorted_list.sort(key=lambda item: item[1])
print(sorted_list)

Output: [('cherry', 1), ('apple', 2), ('banana', 3)]

This code first creates a list of tuples through comprehension and then sorts that list in place with the sort() method, specifying the value as the key with a lambda expression.

Method 4: Using itemgetter and reverse

If you’d like to have the sorted list in descending order, you can utilize the reverse parameter of the sorted() function in combination with the itemgetter utility for a high-performance solution.

Here’s an example:

import operator
my_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
sorted_list = sorted(my_dict.items(), key=operator.itemgetter(1), reverse=True)
print(sorted_list)

Output: [('banana', 3), ('apple', 2), ('cherry', 1)]

By setting reverse=True, the list is sorted in descending order. Combined with itemgetter(1), it sorts the dictionary by values.

Bonus One-Liner Method 5: Using List Comprehension and sorted()

A quick one-liner can achieve the same result by combining a list comprehension with the sorted() function, allowing us to write very compact code for the same task.

Here’s an example:

my_dict = {'apple': 2, 'banana': 3, 'cherry': 1}
sorted_list = sorted([(k, v) for k, v in my_dict.items()], key=lambda item: item[1])
print(sorted_list)

Output: [('cherry', 1), ('apple', 2), ('banana', 3)]

This one-liner compresses the key steps into a single line: a list comprehension to create the tuple pairs and the sorted() function to sort them.

Summary/Discussion

  • Method 1: Using the sorted() Function and a Lambda Expression. Highly readable and Pythonic. May be slightly slower for large datasets due to lambda expression overhead.
  • Method 2: Using the operator Module. More performant than lambda, especially with large datasets. Slightly less readable to those unfamiliar with the module.
  • Method 3: Dictionary Comprehension and sort(). Offers in-place sorting. It is a two-step process which could be less efficient than other methods.
  • Method 4: Using itemgetter and reverse. Perfect for descending order sorts. Uses built-in functions for performance, but may introduce complexity for simple tasks.
  • Bonus Method 5: Using List Comprehension and sorted(). A one-liner that’s quick and easy. However, compactness can come at the cost of readability for some.