A Guide to Python Dictionary Comprehension

Dictionary comprehesion allows Python developers to better work with data stored in dictionaries.

However, dictionary comprehension is often glossed over in introductory Python material.

This tutorial will teach you how to use Python dictionary comprehension to simplify your codebase and become a better Python developer.

What is a Dictionary?

There are four built-in data structures in Python:

Each data structure is best optimized to solve certain problems. In this tutorial, our focus will be on using dictionaries in Python.

Lists are most common data type used to store groups of objects. In lists, elements are extracted with the help of unique indexes that point to each position of the list.

Dictionaries are similar to lists with one major difference. Values are stored in key-value pairs and accessed using keys instead of indexes. Each key is unique in a dictionary. This key uniqueness makes dictionaries a more appropriate data structure when dealing with certain types of problems.

We'll be discussing dictionaries in depth for the remainder of this tutorial. More specifiacally, you will:

  • Learn about dictionaries and how to use them
  • Using dictionary comprehension
  • Using conditional statements in dictionary comprehension
  • Replace lambda functions and loops with dictionary comprehension

Let’s start by explaining how and where you can use dictionaries.

What is a Dictionary?

A dictionary in Python is a data structure that stores key-value pairs. Dictionary values are accessed using unique keys instead of indexes (like in a list).

The easiest way to understand dictionaries with the help of a real life example.

Consider a system where you want to store a list of names of the users and their passwords. You can store it in a list and retrieve the results using the indexes. However, remembering indexes is not that easy. You would need to remember a specific index (which is just a number) for each user.

A better alternative would be to use the name of the user to extract the relevant password. This can be implemented with the help of dictionaries. With dictionaries, you can input a specific key to extract a particular values from the list.

The keys in a dictionary need to be hashable. This means that running the key through a special hash function should return a unique output.

Data types such as integers, floats, strings, tuples and frozensets are hashable. Lists, dictionaries and sets are not hashable. In practical terms, this means that you cannot set lists, dictionaries and sets as keys in a dictionary.

Creating and manipulating dictionaries is pretty straightforward in Python. Consider the following code block:

user_gender = {'jack':'male','john':'male','jean':'female'}

print(user_gender['jack'])

Here, the dictionary user_gender is created, which stores three users and their genders. The name of the users are the dictionary's keys and their genders are the values stored alongside each keys.

Running this code would give the following output:

male

Now let’s see what will happen if you try to access the value of jack by using the index instead of the key:

print('Gender of Jack:', user_gender['0'])

Run it and it will output the following error:

Traceback (most recent call last):
  File ".\dict.py", line 5, in <module>
    print('Gender of Jack:', user_gender['0'])
KeyError: '0'

dict.py is the name of the python file that is being run. You can see that it gives a KeyError exception, which shows that there is no key 0.

What Can You Store In A Dictionary?

While keys have to be hashable in a dictionary, there is no similar conditions for dictionary values. This means you can store almost anything in the values of a dictionary, including:

  • other dictionaries
  • lists
  • other complex data types

Here’s a complex dictionary that contains mixed data types.

mixed_dict = {'one':1, 'two':'two', 'three':[4,'four']}

print(mixed_dict)

If you run this code, you’ll get the whole dictionary printed out:

{'one': 1, 'two': 'two', 'three': [4, 'four']}

In the third entry, the dictionary contains a list. If you’re wondering how you can access the elements present inside this list, this is how:

third_elem = mixed_dict['three']

print(third_elem[0])

Python makes this easy. You just extract the third element and then access the index of the list.

An even better way to do this would be to write it on a single line using chained square brackets, like this:

print(mixed_dict['three'][0])

Here you are accessing the third element of the dictionary and then accessing the first index of what is stored in the third element. In this case, this accesses the integer 4.

Python has a lot of built-in functions for dictionaries that will help you write efficient code.

To update the values of a dictionary, simply access them and overwrite the existing value by using their corresponding keys. You can also extract the values and keys of the dictionary by using inbuilt functions. Here’s how you can do all of this:

print(mixed_dict)
mixed_dict['two'] = 'Three Thousand' 
print(mixed_dict)

keys = mixed_dict.keys()
values = mixed_dict.values()
print('\nAll of keys:',keys)
print('All of values:',values)

This will yield the following output:

{'one': 1, 'two': 'two', 'three': [4, 'four']}
{'one': 1, 'two': 'Three Thousand', 'three': [4, 'four']}

All of keys: dict_keys(['one', 'two', 'three'])
All of values: dict_values([1, 'Three Thousand', [4, 'four']])

As you’ll notice, the value corresponding to the key ‘two’ has been updated. We also printed all of the keys and all of the values from the dictionary.

You can delete specific values or clear the whole dictionary by using the following commands:

del(mixed_dict['one'])
print(mixed_dict)

mixed_dict.clear()
print(mixed_dict)

The key-value pair of ‘one’ has been deleted with the first line of the code.

On the second line of code, the clear() command empties the whole dictionary.

Running this code will yield the following output:

{'two': 'two', 'three': [4, 'four']}
{}

The empty curly brackets indicate an empty dictionary.

Dictionary Comprehension

Python supports dictionary comprehension, which allows developers to create dictionaries in a more intuitive manner.

Dictionary comprehension lets you create new dictionaries from existing dictionaries or from any other data.

The way it works is by filtering out elements from one dictionary to make a new one. Dictionary comprehensions do this by including conditional statements to produce a new dictionary that contains only selective elements from the previous ones.

The main benefit of using dictionary comprehensions is its brevity. A well-written dictionary comprehension can replace multiple for loops and lambda functions. It also improves the readability of your code.

Let’s consider a practical example to understand the benefits of using dictionary comprehension. First, let's consider a script that does not use dictionary comprehension:

dict_cube = dict()

for i in range(10):
    if(i%3 == 0):
        dict_cube[i] = i**3

print(dict_cube)

In this code, a dictionary is being created that stores the cube of all numbers within the range of 10 that are divisible by 3.

Running this code will yield the following output:

{0: 0, 3: 27, 6: 216, 9: 729}

Now here’s how you can do the same thing by using dictionary comprehensions:

dict_cube = {num:num**3 for num in range(10) if num%3 == 0}

print(dict_cube)

You just turned four lines of code into one very concise and meaningful line of code that is easy to understand and gets the job done. It will print the same output. By using the dictionary comprehensions, you can replace loops like shown in the previous code block.

You can also replace lambda functions. Here is an example:

# Points in miles
miles = {'p1':2,'p2':40,'p3':15,'p4':7.5}

# Getting the kilometre values and converting to int
kilometers = list(map(lambda x: int(x*1.60934), miles.values()))

# kilometer dictionary
kilo_dict = dict(zip(miles.keys(),kilometers))

print(kilo_dict)

Let's break this code block down so you fully understand what's happening.

Suppose you have a dictionary that contains four points and their distances (in miles) from your starting point. This script converts these distances to kilometers by using a lambda function.

More specifically, map() iterates through the values of the dictionary miles and applies the lambda function. The results are stored in a list. The zip() function connects the keys to the kilometre values.

Running this code will yield:

{'p1': 3, 'p2': 64, 'p3': 24, 'p4': 12}

You can do the same thing with the help of dictionary comprehensions and use much less code:

# kilometer dictionary

kilo_dict = {num:int(val*1.60934) for (num,val) in miles.items()}
print(kilo_dict)

Using dictionary comprehension, you have managed to significantly reduce the complexity of your code.

Final Thoughts

This tutorial taught you the fundamentals of Python dictionaries and how you can use dictionary comprehension to write better code.

Like anything, dictionary comprehension has a time and a place. With that said, they are extremely useful when used properly.


Written on July 4th, 2020