5 Best Ways to Sort Python Dictionaries by Key or Value

πŸ’‘ Problem Formulation: When working with dictionaries in Python, there may be situations where you need to arrange the contents either by key or by value for easier data manipulation or presentation. For example, given a dictionary {'apple': 5, 'banana': 3, 'cherry': 7}, you might want to sort by key to obtain {'apple': 5, 'banana': 3, 'cherry': 7}, or by value to get {'banana': 3, 'apple': 5, 'cherry': 7}.

Method 1: Using the sorted() Function and Dictionary Comprehension

This method involves using the built-in sorted() function to sort the dictionary keys or values and then creating a new dictionary in the sorted order using dictionary comprehension. It’s a clean and readable way to sort dictionaries in Python.

Here’s an example:

d = {'apple': 5, 'banana': 3, 'cherry': 7}
sorted_dict = {k: d[k] for k in sorted(d.keys())}

Output:

{'apple': 5, 'banana': 3, 'cherry': 7}

The code snippet sorts the dictionary d by its keys using the sorted() function, which returns a sorted list of keys that is then used to construct a new dictionary with the same values, but ordered keys.

Method 2: Sorting with the items() Method and sorted()

Another approach to sorting a dictionary is to utilize the items() method to get key-value pairs, which can then be sorted using the sorted() function. This method is particularly useful for sorting dictionaries by value.

Here’s an example:

d = {'apple': 5, 'banana': 3, 'cherry': 7}
sorted_items = sorted(d.items(), key=lambda item: item[1])
sorted_dict = dict(sorted_items)

Output:

{'banana': 3, 'apple': 5, 'cherry': 7}

This snippet sorts the dictionary by values. The items() method returns an iterable with key-value tuples. These tuples are sorted by their second element (value) using a lambda function and sorted(), and then converted back into a dictionary.

Method 3: Using OrderedDict from the collections Module

An OrderedDict is a dictionary subclass that remembers the order in which its contents are added, which can be utilized to sort a dictionary. This was more useful before Python 3.7 when dictionaries were not guaranteed to be ordered.

Here’s an example:

from collections import OrderedDict
d = {'apple': 5, 'banana': 3, 'cherry': 7}
ordered_dict = OrderedDict(sorted(d.items()))

Output:

OrderedDict([('apple', 5), ('banana', 3), ('cherry', 7)])

This code sorts the dictionary d by keys using the sorted() function and then creates an OrderedDict that maintains the sorted order of the keys.

Method 4: Sorting In-Place with sorted() and Dictionary Update

In Python 3.7 and above, dictionaries retain their insertion order. This means it’s possible to sort a dictionary in-place by sorting its items and updating the original dictionary with the sorted items.

Here’s an example:

d = {'apple': 5, 'banana': 3, 'cherry': 7}
d.update(sorted(d.items()))

Output:

{'apple': 5, 'banana': 3, 'cherry': 7}

The code snippet sorts the dictionary items and uses the update() method to update the original dictionary, thus keeping it in the sorted order.

Bonus One-Liner Method 5: Using a Lambda Function in Sorted

A one-liner solution can be achieved by combining sorted(), lambda, and dictionary comprehension. It’s concise but may sacrifice some readability for beginners.

Here’s an example:

d = {'apple': 5, 'banana': 3, 'cherry': 7}
sorted_dict = dict(sorted(d.items(), key=lambda item: item[0]))

Output:

{'apple': 5, 'banana': 3, 'cherry': 7}

This one-liner applies a lambda function to sort the dictionary by its keys and immediately casts the sorted list of tuples back to a dictionary.

Summary/Discussion

  • Method 1: Sorted Function with Dictionary Comprehension. It’s readable and explicit about the sorting process. However, it’s less concise than some one-liner methods.
  • Method 2: items() Method and Sorted Function. It provides an elegant way to sort by value and is very clear in its intent. A drawback is a slightly longer syntax.
  • Method 3: Using OrderedDict. It’s less relevant for newer Python versions but still useful for maintaining ordered dictionaries in earlier Python versions. It may be unnecessarily verbose for Python 3.7 and later.
  • Method 4: Sorting In-Place. This maintains the original dictionary object, which could be useful in some scenarios but changes the original data, which might not be desirable in all cases.
  • Method 5: Lambda Function in Sorted. This method is great for writing compact code, but it may compromise readability for those not familiar with lambda functions.