Introduction
Dictionaries are a flexible Python data type for storing key-value pairs. Although there are many ways to modify and initialize a Python dictionary, one of the most efficient ways is to use dictionary comprehension.
The method works with dictionaries in a compact, single-line format. Both new and advanced Python programmers benefit from learning how dictionary comprehension works.
This guide explains dictionary comprehension and how to best utilize this technique in Python.
Prerequisites
- Python 3 installed.
- An IDE or code editor to run code examples.
What Is Python Dictionary Comprehension?
Dictionary comprehension is a technique for creating Python dictionaries in one line. The method creates dictionaries from iterable objects, such as a list, tuple, or another dictionary. Dictionary comprehension also allows filtering and modifying key-value pairs based on specified conditions.
The syntax for dictionary comprehension looks like the following example:
result = {key: value for item in iterable}
The line consists of the following elements:
key
is an expression that applies to an item to generate keys.value
is an expression that applies to an item to generate values.item
is an element from an existing iterable.iterable
is a list, tuple, or another iterable from which the items are extracted.
Dictionary comprehension has a similar syntax to list comprehension.
Why Use Dictionary Comprehension?
Learning and using dictionary comprehension in Python has many benefits. Some of them are:
- Readability. Dictionary comprehension is a compact and concise way to create dictionaries. The syntax avoids using lengthy conditionals and loops and instead uses elegant one-liners.
- Efficiency. Dictionary comprehension is preferable to other methods when creating new dictionaries from iterables. Its optimized performance makes it more efficient than other dictionary creation methods.
- Data filtering and transformation. The method enables extracting, modifying, and filtering data based on specified conditions. Dictionary comprehension simplifies data transformations and restructuring existing data collections.
Overall, dictionary comprehension is a simple and Pythonic way to create dictionaries. Only use this method if the statements are easily read and understood at first glance. The idea is to aim for simplicity.
Python Dictionary Comprehension Methods
There are different ways to use dictionary comprehension in Python. The different methods use various functions and approaches to generate a dictionary.
The sections below cover different dictionary comprehension methods through examples.
Creating a Dictionary from an Existing Dictionary
Use dictionary comprehension to make a new dictionary from an existing one. For example:
my_dictionary = {"a": 1, "b": 2, "c": 3, "d": 4}
new_dictionary = {my_dictionary[key]:key for key in my_dictionary}
print(new_dictionary)
The code creates a new dictionary from an existing dictionary. The new dictionary exchanges the key-value pairs, and the keys in the old dictionary become values in the new one.
Using the items() Method
The items()
method provides a view of key-value pairs in a dictionary. Use this method to extract the keys and values automatically.
my_dictionary = {"a": 1, "b": 2, "c": 3, "d": 4}
new_dictionary = {value:key for (key,value) in my_dictionary.items()}
print(new_dictionary)
The method extracts the key-value pairs and rotates them to generate a new dictionary.
Creating a Dictionary from One Iterable
Dictionary comprehension allows creating a dictionary from one iterable object. For example, use a list and apply different operations to generate keys and values. The code below demonstrates how to create a list that contains numbers and their squares:
numbers = [1, 2, 3, 4, 5]
numbers_squares = {number:number**2 for number in numbers}
print(numbers_squares)
The method creates key-value pairs, where the keys are numbers, and the values are their squares.
Alternatively, create a list with strings and use dictionary comprehension to map the number of characters to each string. For example:
words = ["I'm", "sorry", "Dave"]
words_characters = {word:len(word) for word in words}
print(words_characters)
The resulting dictionary contains words as keys and character lengths as values.
Creating a Dictionary from Two Iterables
A common task is to map two iterables into a dictionary. Use dictionary comprehension and the zip()
method to accomplish this task in an easy one-liner. For example:
numbers = [1, 2, 3, 4]
words = ["a", "b", "c", "d"]
numbers_words = {number:word for number, word in zip(numbers, words)}
print(numbers_words)
Alternatively, to avoid using the zip()
method, generate a number range based on the list length, and iterate through the lists. For instance:
numbers = [1, 2, 3, 4]
words = ["a", "b", "c", "d"]
numbers_words = {numbers[i]:words[i] for i in range(len(numbers))}
print(numbers_words)
In both examples, additional functions help iterate through lists to extract elements. Dictionary comprehension helps generate a dictionary based on the extracted information.
How to Add Conditionals to Dictionary Comprehension
Adding conditionals to dictionary comprehension lets you filter or modify items before including them in the final dictionary. Below are examples of implementing different conditional statements to apply filters to dictionary comprehension.
If Condition
Add a single if
condition to exclude elements that do not pass the conditional check. The example below shows how to generate a dictionary that includes only even numbers as keys and their squares as a value:
numbers = [1, 2, 3, 4, 5]
numbers_squares = {number:number**2 for number in numbers if number%2 == 0}
print(numbers_squares)
The if
condition checks if the element from the list is divisible by two before adding it to the dictionary.
Multiple If Conditions
Use multiple if
conditions with the and
or or
operators to create a chain of several conditional statements. For example:
numbers = [1, 2, 3, 4, 5]
numbers_squares = {number:number**2 for number in numbers if number%2 == 0 or number > 3}
print(numbers_squares)
The resulting dictionary contains numbers divisible by two or greater than three as keys and their squares as values.
If-Else Conditions
Adding an if
-else
condition to dictionary comprehension provides a fallback case when the if
statement evaluates to false. For example:
numbers = [1, 2, 3, 4, 5]
numbers_squares = {number:number**2 if number%2 == 0 else number for number in numbers}
print(numbers_squares)
The dictionary comprehension statement checks if a number is divisible by two. It adds a number and its square as a key-value pair divisible. If the number is not divisible by two, it adds the number as both the key and value.
The resulting dictionary contains key-value pairs, whose values are squared if the key is an even number.
Nested Dictionary Comprehension
For complex use cases, dictionary comprehension allows nesting statements to create multi-level dictionaries. Below is an example nested dictionary created using dictionary comprehension:
numbers = [1, 2, 3, 4, 5]
nested = {number:{n**2:n**3 for n in numbers if n == number} for number in numbers}
print(nested)
The code generates dictionary values using dictionary comprehension. The resulting code outputs a multi-level dictionary where the keys are a number while the values are a key-value pair of the same number squared and cubed.
Conclusion
After reading this guide, you know what dictionary comprehension is and how to use it in your code. Use dictionary comprehension as a convenient and fast way to generate a dictionary from another iterable.
Next, learn different ways to add items to a dictionary.