Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 23442

Real Python: Sorting a Python Dictionary: Values, Keys, and More

$
0
0

Sorting a Python dictionary involves organizing its key-value pairs in a specific order. To sort a Python dictionary by its keys, use the sorted() function combined with .items(). This approach returns a list of tuples sorted by keys, which you can convert back to a dictionary using the dict() constructor. Sorting by values requires specifying a sort key using a lambda function or itemgetter().

You can sort a Python dictionary in descending order by setting the reverse argument of the sorted() function to True. Sorting dictionaries with non-comparable keys or values can be challenging, but you can manage it by providing default values or using a custom sort key.

By the end of this tutorial, you’ll understand that:

  • You can sort a dictionary by its keys using sorted() with .items() and dict().
  • To sort by values, you use sorted() with a key function like lambda or itemgetter().
  • Sorting in descending order is possible by setting reverse=True in sorted().
  • For non-comparable keys or values, you use default values or custom sort keys.
  • Python dictionaries can’t be sorted in-place, so you need to create a new sorted dictionary.

Read on to learn how to effectively sort dictionaries using these techniques and the strategic implications of choosing the right data structure for your key-value data. But first, you’ll learn some foundational knowledge that will help you understand how to sort a dictionary in Python.

Free Download:Click here to download the code that you’ll use to sort key-value pairs in this tutorial.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries were inherently unordered. A Python dictionary is an implementation of the hash table, which is traditionally an unordered data structure.

As a side effect of the compact dictionary implementation in Python 3.6, dictionaries started to conserve insertion order. From 3.7, that insertion order has been guaranteed.

If you wanted to keep an ordered dictionary as a data structure before compact dictionaries, then you could use OrderedDict from the collections module. Similar to the modern compact dictionary, it also keeps insertion order, but neither type of dictionary sorts itself.

Another alternative for storing an ordered key-value pair data is to store the pairs as a list of tuples. As you’ll see later in the tutorial, using a list of tuples could be the best choice for your data.

An essential point to understand when sorting dictionaries is that even though they conserve insertion order, they’re not considered a sequence. A dictionary is like a set of key-value pairs, and sets are unordered.

Dictionaries also don’t have much reordering functionality. They’re not like lists, where you can insert elements at any position. In the next section, you’ll explore the consequences of this limitation further.

Understanding What Sorting a Dictionary Really Means

Because dictionaries don’t have much reordering functionality, when sorting a dictionary, it’s rarely done in-place. In fact, there are no methods for explicitly moving items in a dictionary.

If you wanted to sort a dictionary in-place, then you’d have to use the del keyword to delete an item from the dictionary and then add it again. Deleting and then adding again effectively moves the key-value pair to the end.

The OrderedDict class has a specific method to move an item to the end or the start, which may make OrderedDict preferable for keeping a sorted dictionary. However, it’s still not very common and isn’t very performant, to say the least.

The typical method for sorting dictionaries is to get a dictionary view, sort it, and then cast the resulting list back into a dictionary. So you effectively go from a dictionary to a list and back into a dictionary. Depending on your use case, you may not need to convert the list back into a dictionary.

Note: Sorted dictionaries aren’t a very common pattern. You’ll explore more about that topic later in the tutorial.

With those preliminaries out of the way, you’ll get to sorting dictionaries in the next section.

Sorting Dictionaries in Python

In this section, you’ll be putting together the components of sorting a dictionary so that, in the end, you can master the most common way of sorting a dictionary:

Python
>>> people={3:"Jim",2:"Jack",4:"Jane",1:"Jill"}>>> # Sort by key>>> dict(sorted(people.items())){1: 'Jill', 2: 'Jack', 3: 'Jim', 4: 'Jane'}>>> # Sort by value>>> dict(sorted(people.items(),key=lambdaitem:item[1])){2: 'Jack', 4: 'Jane', 1: 'Jill', 3: 'Jim'}
Copied!

Don’t worry if you don’t understand the snippets above—you’ll review it all step-by-step in the following sections. Along the way, you’ll learn how to use the sorted() function with sort keys, lambda functions, and dictionary constructors.

Using the sorted() Function

Read the full article at https://realpython.com/sort-python-dictionary/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]


Viewing all articles
Browse latest Browse all 23442

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>