course
Python Dictionary Comprehension: Essentials You Need to Know
Dictionaries (or dict
in Python) are a way of storing elements just like you would in a Python list. But, rather than accessing elements using its index, you assign a fixed key to it and access the element using the key. What you now deal with is a "key-value" pair, which is sometimes a more appropriate data structure for many problems instead of a simple list. You will often have to deal with dictionaries when doing data science, which makes dictionary comprehension a skill that you will want to master.
In this tutorial:
- First, you'll see what a Python dictionary really is and how you can use it effectively.
- Next, you'll learn about Python dictionary comprehensions: you will see what it is, why it is important, and how it can serve as an alternative to for loops and lambda functions.
- You will learn how to add conditionals into dictionary comprehensions: you will work with if conditions, multiple if conditions, and also if-else statements.
- Lastly, you will see what nested dictionary comprehension is, how you can use it, and how you can potentially rewrite it with for loops.
To easily run all the example code in this tutorial yourself, you can create a DataLab workbook for free that has Python pre-installed and contains all code samples. For more practice on dictionary comprehension, check out our Python Toolbox interactive course.
Learn Python From Scratch
What is a Python Dictionary?
A dictionary in Python is a collection of items accessed by a specific key rather than by an index. What does this mean?
Imagine a dictionary in the real world. When you need to look up the meaning of a word, you try to find the meaning using the word itself and not the possible index of the word. Python dictionaries work with the same concept: The word whose meaning you are looking for is the key, and the meaning of the word is the value. You do not need to know the index of the word in a dictionary to find its meaning.
Initializing a dictionary in Python
You can initialize a dictionary in Python this way:
a = {'apple': 'fruit', 'beetroot': 'vegetable', 'cake': 'dessert'}
a['doughnut'] = 'snack'
print(a['apple'])
fruit
print(a[0])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-9-00d4a978143a> in <module>() ----> 1 print(a[0]) KeyError: 0
First, we create a dictionary named a
that has three key-value pairs: 'apple': 'fruit'
, 'beetroot': 'vegetable'
, and 'cake': 'dessert'
. The keys are strings that represent the names of items, and the values are strings that represent the type or category of the item.
Next, we add a new key-value pair to the dictionary a
using the syntax a ['doughnut'] = 'snack'
. This adds the key 'doughnut'
to the dictionary with the corresponding value 'snack'
.
The third line of the code prints the value associated with the key 'apple'
in the dictionary a
. Since 'apple'
is a key in the dictionary, the code prints the value 'fruit'
.
The fourth line of the code tries to print the value associated with the key 0
in the dictionary a
, which is not a valid key in the dictionary. This results in a KeyError
, which is raised when trying to access a key that does not exist in a dictionary.
Python dictionary data types
The items in a dictionary can have any data type. Check out some more examples of a dictionary below to get a hang of it:
Create a dictionary a
with four key-value pairs:
a = {'one': 1, 'two': 'to', 'three': 3.0, 'four': [4,4.0]}
print(a)
Update the value associated with the key 'one'
in the dictionary a to 1.0
.
# Update a dictionary
a['one'] = 1.0
print(a)
{'four': [4, 4.0], 'two': 'to', 'three': 3.0, 'one': 1.0}
Delete the key-value pair associated with the key 'one'
from the dictionary a
.
# Delete a single element
del a['one']
print(a)
{'four': [4, 4.0], 'two': 'to', 'three': 3.0}
Remove all key-value pairs from the dictionary a
using the clear()
method.
# Delete all elements in the dictionary
a.clear()
print(a)
{}
Delete the dictionary a
using the del
keyword.
# Delete the dictionary
del a
print(a)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-701c9d6596da> in <module>()
1 del a #Deletes the dictionary
----> 2 print(a)
NameError: name 'a' is not defined
It's important to remember that a key has to be unique in a dictionary; no duplicates are allowed. However, in case of duplicate keys, rather than giving an error, Python will take the last instance of the key to be valid and simply ignore the first key-value pair. See it for yourself:
sweet_dict = {'a1': 'cake', 'a2':'cookie', 'a1': 'icecream'}
print(sweet_dict['a1'])
icecream
Python Dictionary Comprehension
Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary, and each item can be transformed as needed.
A good list comprehension can make your code more expressive and, thus, easier to read. The key to creating comprehensions is to not let them get so complex that your head spins when you try to decipher what they are actually doing. Keeping the idea of "easy to read" alive.
The way to do dictionary comprehension in Python is to be able to access the key
objects and the value
objects of a dictionary.
How can this be done?
Python has you covered! You can simply use the built-in methods for the same:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Put all keys of `dict1` in a list and returns the list
dict1.keys()
dict_keys(['c', 'd', 'a', 'b'])
# Put all values saved in `dict1` in a list and returns the list
dict1.values()
dict_values([3, 4, 1, 2])
The code above creates a Python dictionary called dict1
with four key-value pairs. The keys()
method is called on the dictionary, which returns a view object containing all the keys in the dictionary.
The values()
method is also called on the dictionary, which returns a view object containing all the values in the dictionary.
Both view objects behave like sets and can be used to perform set operations on the keys and values, respectively.
Note that the order of the keys and values in the view objects is not guaranteed to be the same as the order in which they were added to the dictionary.
Basic value transformation
Let's start off with a simple dictionary comprehension:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Double each value in the dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
print(double_dict1)
{'e': 10, 'a': 2, 'c': 6, 'b': 4, 'd': 8}
In the comprehension code above, we create a new dictionary double_dict1
from a dictionary dict1
by simply doubling each value in it.
You can also make changes to the key values. For example, let's create the same dictionary as above but also change the names of the key.
dict1_keys = {k*2:v for (k,v) in dict1.items()}
print(dict1_keys)
{'dd': 4, 'ee': 5, 'aa': 1, 'bb': 2, 'cc': 3}
Using the items() method
So, now that you know how to access all the keys and their values in a dictionary. You can also access each key-value pair within a dictionary using the items()
method:
dict1.items()
dict_items([('c', 3), ('d', 4), ('a', 1), ('b', 2)])
This is the general template you can follow for dictionary comprehension in Python:
dict_variable = {key:value for (key,value) in dictonary.items()}
This can serve as the basic and the most simple template. This can get more and more complex as you add conditionalities to it.
Using the fromkeys() method
Python also offers the fromkeys()
method, which allows you to create dictionaries with a uniform value for a specified set of keys. This method is useful when initializing dictionaries with default values. Take a look:
# Create a dictionary with keys ranging from 0 to 4, all set to True
my_dict = dict.fromkeys(range(5), True)
print(my_dict)
{0: True, 1: True, 2: True, 3: True, 4: True}
In this example, the fromkeys()
method creates a dictionary where the keys are numbers from 0 to 4, and each key is assigned the value True
. This approach simplifies tasks like initializing dictionaries for later updates or processing.
Why Use Dictionary Comprehension?
Dictionary comprehension is a powerful concept and can be used to substitute for
loops and lambda
functions. However, not all for loops can be written as a dictionary comprehension, but all dictionary comprehension can be written with a for loop.
Consider the following problem where you want to create a new dictionary where the key is a number divisible by 2 in a range of 0-10, and it's value is the square of the number.
Let's see how you can solve the same problem using a for loop and dictionary comprehension:
numbers = range(10)
new_dict_for = {}
# Add values to `new_dict` using for loop
for n in numbers:
if n%2==0:
new_dict_for[n] = n**2
print(new_dict_for)
{0: 0, 8: 64, 2: 4, 4: 16, 6: 36}
# Use dictionary comprehension
new_dict_comp = {n:n**2 for n in numbers if n%2 == 0}
print(new_dict_comp)
{0: 0, 8: 64, 2: 4, 4: 16, 6: 36}
Alternative to for loops
For loops are used to repeat a certain operation or a block of instructions in a program for a given number of times. However, nested for loops (for loop inside another for loop) can get confusing and complex. Dictionary comprehensions are better in such situations and can simplify the readability and your understanding of the code.
Tip: check out DataCamp's Loops in Python tutorial for more information on loops in Python.
Alternative to lambda functions
Lambda functions are a way of creating small anonymous functions. They are functions without a name. These functions are throw-away functions, which are only needed where they have been created. Lambda functions are mainly used in combination with the functions filter()
, map()
and reduce()
.
Let's look at the lambda function along with the map()
function:
# Initialize `fahrenheit` dictionary
fahrenheit = {'t1':-30, 't2':-20, 't3':-10, 't4':0}
#Get the corresponding `celsius` values
celsius = list(map(lambda x: (float(5)/9)*(x-32), fahrenheit.values()))
#Create the `celsius` dictionary
celsius_dict = dict(zip(fahrenheit.keys(), celsius))
print(celsius_dict)
{'t2': -28.88888888888889, 't3': -23.333333333333336, 't1': -34.44444444444444, 't4': -17.77777777777778}
A Detailed Python Dictionary Comprehension Example
Let's look at another situation where you want to convert a dictionary of Fahrenheit temperatures into Celsius.
Let's break the code down: first, you need to define a mathematical formula that does the conversion from Fahrenheit to Celsius.
In the code, this is done with the help of the lambda function. You then pass this function as an argument to the map()
function, which then applies the operation to every item in the fahrenheit.values()
list.
Remember the values()
function? It returns a list containing the items stored in the dictionary.
What you have now is a list containing the temperature value in celsius, but the solution requires it to be a dictionary.
Python has a built-in function called zip()
which goes over the elements of iterators and aggregates them. You can read more about the zip()
function in this Python example.
In our example above, the zip function aggregates the item from fahrenheit.keys()
and the celsius
list, giving a key-value pair that you can put together in a dictionary using the dict
function, which is the desired result.
Now, let's try to solve the same problem using dictionary comprehension:
# Initialize the `fahrenheit` dictionary
fahrenheit = {'t1': -30,'t2': -20,'t3': -10,'t4': 0}
# Get the corresponding `celsius` values and create the new dictionary
celsius = {k:(float(5)/9)*(v-32) for (k,v) in fahrenheit.items()}
print(celsius_dict)
{'t2': -28.88888888888889, 't3': -23.333333333333336, 't1': -34.44444444444444, 't4': -17.77777777777778}
Here's a breakdown of what we've created in the code above:
-
Create a dictionary named
fahrenheit
with four key-value pairs representing temperature readings in Fahrenheit. -
Define a new dictionary called
celsius
. -
Use a dictionary comprehension to iterate over the
fahrenheit
dictionary and convert the Fahrenheit temperature readings to Celsius using the formula(5/9) * (F-32)
. -
For each key-value pair in
fahrenheit
, the key is assigned to variablek
and the value is assigned to variablev
. -
The value of the Celsius temperature corresponding to each Fahrenheit temperature is calculated using the formula above and is added as a key-value pair to the
celsius
dictionary. -
The resulting
celsius
dictionary is printed to the console.
As you can see, the problem can be solved with a single line of code using dictionary comprehension as compared to the two-step process and understanding the working of three functions (lambda
, map()
and zip()
) for the first implementation.
Moreover, the solution is intuitive and easy to understand with dictionary comprehension. Hence, dictionary comprehension can serve as a good alternative to the lambda functions.
Adding Conditionals to Dictionary Comprehension
You often need to add conditions to a solution while tackling problems. Let's explore how you can add conditionals into dictionary comprehension to make it more powerful.
If condition
Let's suppose you need to create a new dictionary from a given dictionary but with items that are greater than 2. This means that you need to add a condition to the original template you saw above...
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Check for items greater than 2
dict1_cond = {k:v for (k,v) in dict1.items() if v>2}
print(dict1_cond)
{'e': 5, 'c': 3, 'd': 4}
This isn't so hard! But what if you have multiple conditions?
Multiple if conditions
In the problem above, what if you have to not only get the items greater than 2 but also need to check if they are multiples of 2 at the same time?
dict1_doubleCond = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0}
print(dict1_doubleCond)
{'d': 4}
The solution to adding multiple conditionals is as easy as simply adding the conditions one after another in your comprehension. However, you need to be careful about what you are trying to do in the problem. Remember that the consecutive if statements work as if they had and
clauses between them.
Let's see one more example with three conditionals:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}
dict1_tripleCond = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0 if v%3 == 0}
print(dict1_tripleCond)
{'f': 6}
In a for loop, this will correspond to:
dict1_tripleCond = {}
for (k,v) in dict1.items():
if (v>=2 and v%2 == 0 and v%3 == 0):
dict1_tripleCond[k] = v
print(dict1_tripleCond)
{'f': 6}
If-else conditions
Dealing with an if-else condition is also easy with dictionary comprehension. Check out the following example to see it for yourself:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}
# Identify odd and even entries
dict1_tripleCond = {k:('even' if v%2==0 else 'odd') for (k,v) in dict1.items()}
print(dict1_tripleCond)
{'f': 'even', 'c': 'odd', 'b': 'even', 'd': 'even', 'e': 'odd', 'a': 'odd'}
Nested dictionary comprehension
Nesting is a programming concept where data is organized in layers or where objects contain other similar objects. You must have often seen a nested 'if' structure, which is an if condition inside another if condition.
Similarly, dictionaries can be nested, and thus, their comprehensions can be nested as well. Let's see what this means:
nested_dict = {'first':{'a':1}, 'second':{'b':2}}
float_dict = {outer_k: {float(inner_v) for (inner_k, inner_v) in outer_v.items()} for (outer_k, outer_v) in nested_dict.items()}
print(float_dict)
{'first': {1.0}, 'second': {2.0}}
This is an example of a nested dictionary. The nested_dict
is a dictionary with the keys: first
and second
, which hold dictionary objects in their values. The code works with the inner dictionary values, converts them to float, and then combines the outer keys with the new float inner values into a new dictionary.
The code also has a nested dictionary comprehension, which is dictionary comprehension inside another one. The dictionary comprehension, when nested, can get pretty hard to read as well as understand, which takes away the whole point of using comprehensions in the first place.
As the structure of the dictionary you are working with gets complicated, the dictionary comprehension starts to get complicated as well. For such situations, you might be better off not using complicated comprehensions in your code.
Note that you can rewrite the above code chunk also with a nested for loop:
nested_dict = {'first':{'a':1}, 'second':{'b':2}}
for (outer_k, outer_v) in nested_dict.items():
for (inner_k, inner_v) in outer_v.items():
outer_v.update({inner_k: float(inner_v)})
nested_dict.update({outer_k:outer_v})
print(nested_dict)
{'first': {'a': 1.0}, 'second': {'b': 2.0}}
Final Thoughts
Hopefully, you have now learned about dictionaries in Python, the concept of comprehension, and why and where Python dictionary comprehension can be useful.
Practice makes your Python better! Check out some of our top Python tips and tricks to improve your code, or take our Python Data Fundamentals track to master the most important stuff.
Python Dictionary Comprehension FAQs
What is dictionary comprehension in Python?
Dictionary comprehension is a concise and readable way to create dictionaries in Python. It provides a way to create a new dictionary from an iterable object like a list, tuple, or set.
What is the syntax for dictionary comprehension in Python?
The syntax for dictionary comprehension in Python is as follows: {key:value for (key,value) in iterable}
How do I create a dictionary from a list using dictionary comprehension in Python?
You can create a dictionary from a list using dictionary comprehension in Python by iterating over the list and setting the list elements as keys and values in the new dictionary.
Can I use conditional statements in dictionary comprehension in Python?
Yes, you can use conditional statements in dictionary comprehension in Python to filter out certain elements.
What are the benefits of using dictionary comprehension in Python?
The benefits of using dictionary comprehension in Python are that it is concise, readable, and reduces the amount of code needed to create dictionaries. It also allows for filtering and transformation of dictionary elements in a single line of code.
I have worked in various industries and have worn multiple hats: software developer, machine learning researcher, data scientist, product manager. But at the core of it all, I am a programmer who loves to learn and share knowledge!
Python Courses
course
Introduction to Data Science in Python
course
Intermediate Python
cheat-sheet
Python For Data Science Cheat Sheet For Beginners
tutorial
Python List Comprehension Tutorial
tutorial
Python Dictionaries Tutorial: The Definitive Guide
tutorial
Python Dictionary Tutorial
DataCamp Team
14 min
tutorial