The dictionary is one of Python’s most important data types. So if you’re looking to master the Python language, you’ll need to know the ins and outs of dictionaries. 

In this article, we show you how to work with dictionaries, illustrating both fundamental and advanced techniques.

What Is a Python Dictionary?

In Python, a dictionary is an unordered collection of key-value pairs. The dictionary’s unordered nature means that the items within it aren’t stored in any particular order, and thus can’t be accessed by a position as they would in a list. Rather, you could retrieve a dictionary’s elements by indexing a dictionary with a key. Each key in a Python dictionary is unique and has an associated value, which the dictionary returns when presented with a key.

If you’ve written code in another programming language like JavaScript or C, you might find the description above familiar – Python dictionaries are no different from associative arrays, hashmaps or lookup tables. Dictionaries are among the most useful data types given their fast and efficient performance. They’re used to solve an array of problems – even Python classes are just dictionaries under the hood!

Let’s look over a basic code example of a dictionary.

Creating a Python Dictionary

Python dictionaries may be created with either curly braces or by using the dict() function.

The curly braces method requires separating the keys and values with a colon, and key-value pairs with a comma. The below template is illustrative.

It’s important to know that keys are limited to hashable data types (strings, numbers, and tuples) and must be unique within a single dictionary. In contrast, values don’t have to be unique and may come from any data type – they can even come from another dictionary. 

Using the syntax above, let’s create a dictionary that contains information about Dostoevsky’s “Crime and Punishment.”

The dictionary’s construction corresponds to its structure when printed out on the screen.

Alternatively, you could create a dictionary using Python’s dict() function by providing the function a list of tuples containing a key and a value separated by a comma. The example below illustrates this approach.

There’s no difference between the two methods; both will construct the same dictionary, so you may use either at your discretion. Note that you could also create an empty dictionary. Creating an empty dictionary is useful if you don’t want to populate it with items right away.

Accessing a Dictionary’s Elements

After you create a dictionary, you might want to access its values. You may access a Python dictionary’s elements by specifying a key inside square brackets after the dictionary’s name. The key that you provide inside the brackets specifies the key-value pair that’s being accessed.

Once you retrieve a value, you can perform all operations that pertain to the value’s data type. In the dictionary above, genres are contained within a list data type, so all list operations (such as positional indexing) apply to it. Let’s take a look at a couple of examples.

If you try to access a Python dictionary using a key that doesn’t exist in that dictionary, your Python interpreter will raise an error:

To avoid receiving an error, you can check whether the key exists in the dictionary before you try using it. One way to do so is by using the in operator. It’ll return the response True if the dictionary contains the key and False otherwise. In the example below, the program will execute the print statement only if the key “Language” exists in the dictionary.

Alternatively, Python dictionaries provide for the get() method. This method allows you to specify the default value to be returned in case the key provided doesn’t exist in the dictionary.

Populating a Python Dictionary

In the example above, we created a dictionary by providing all items at once. However, building dictionaries is more often an incremental process. You can update a dictionary with the following syntax:

Updating a dictionary in this way adds a new key-value pair for keys that don’t already exist in the dictionary, and for keys that do, updating replaces their existing values with the new ones. In the example below, we’ll enhance our dictionary to include more information about the novel:

We can print the dictionary to make sure it reflects our addition:

The update() Method

Sometimes you might want to populate one dictionary with values from another. One way you could do so is by iterating over the new dictionary’s key-value pairs and adding each pair using the syntax above. Another way would be by using the update() method with the following syntax:

update() takes an iterable of key-value pairs or another dictionary as its argument. This method adds a key-value pair if a key doesn’t already exist in the target dictionary, and updates the existing value for a key that does.

Now let’s say we want to change our book’s ratings. We’ll create a new dictionary that contains the updated ratings, making sure that the rating keys are the same as in the target dictionary. Then, using the method above, we’ll update our dictionary.

Now, let’s print the ratings to make sure they’ve been updated.

Traversing a Python Dictionary

You’ll often find yourself in situations where it’s necessary to iterate over a dictionary’s elements. Python provides some useful tools for doing this.

The most straightforward way to iterate over a dictionary is with a for loop. By default, a for loop will iterate over the dictionary’s keys. Alternatively, you can specify whether you want to iterate through keys, values, or key-value pairs using the keys(), values(), and items() methods, respectively.

In the example below, we traverse through our dictionary and print all of its preexisting key-value pairs. Since a for loop iterates through keys by default, we’ll access the values as usual, by specifying a key inside square brackets.

We can also achieve the same result with the items() method, which returns an iterable of tuples containing key-value pairs:

Sorting a Python Dictionary

It’s often necessary to sort elements within a dictionary. Let’s create a Python dictionary that contains the birth years of some famous writers and sort it using the sorted() method:

Sorting single values is easy:

However, we’ll more often want to sort the dictionary, either by keys or by values, while preserving the pairings. Let’s take a look at how this can be done.

Recall that items() return a sequence of key-value pairs contained within a tuple, with the key in the first position and the value in the second. sorted() assumes by default that we want to sort the sequence per the first element. Therefore, in the output, the dictionary is sorted by keys.

In the code snippet below, we’ll use the same method, but providing the parameter key with an argument in the form of a Python anonymous function. This function specifies that we’d like to sort the sequence per the element positioned at index 1, which is the position of the value in the tuple.

As a result, the dictionary is sorted by years, in ascending order. Providing reverse=True to the method call will sort the elements in descending order:

Note that the dictionary will be sorted based on the data types it contains. Strings are sorted alphabetically whereas numbers are sorted in ascending order. If keys or values consist of different data types that have no way of being compared with one another, such as numbers and strings, your Python interpreter will raise an error.

Learn More

In this article, we covered both basic and advanced strategies for working with Python dictionaries. Knowing how to work with dictionaries is indispensable to any programmer’s toolkit, but there’s much more you’ll need to learn to master Python. 

Check out our Intro to Programming Nanodegree, a program that could very well be your first step towards careers in Web and App Development, Machine Learning, Data Science, AI, and more.

Start Learning