Dictionary comprehension is the third type of comprehension in Python. It is a short-hand and powerful technique of creating a new dictionary from an existing dictionary or other iterable objects, such as list or tuple.
Dictionary comprehension was introduced in the Python 2.0 version, but started his life in Python 3.0 version. It has since become a popular technique among Python developers.
With dictionary comprehension, we can create a new iterable dictionary object in an easy, concise and expressive way.
It provides a compact and elegant syntax to create a new dictionary by iterating over an existing iterable object and applying conditions to its elements.
Syntax for Dictionary Comprehension in Python
A dictionary comprehension generates or returns a new dictionary from an iterable object that satisfies the specified condition. It contains an expression and a for loop with an optional condition enclosed in curly braces like set comprehension. Hence, dictionary comprehension supports two syntaxes:
new_dict = {key_expr : value_expr for itr_var in iterable} new_dict = {key_expr : value_expr for itr_var in iterable if condition}
In the above syntaxes, new_dict is the name of resulting dictionary. Since a dictionary consists of key-value pairs, dictionary comprehension includes two expressions separated by a colon: key_expr and value_expr.
The key_expr and value_expr define the key-value pairs of the resulting dictionary. The key_expr evaluates to the key and value_expr evaluates to the corresponding value.
The for loop iterates over each element of the iterable object. The itr_var represents each element in the iterable, which is usually used to generate the key-value pairs. In other words, the key_expr and value_expr usually involve the iterating variable iterating_var to generate the key-value pairs.
In the second syntax, if condition filters elements of a sequence, only if they meet the condition provided by the conditional expression during iteration.
Examples of Dictionary Comprehension
Let’s look at some examples to better understand dictionary comprehension.
Example 1: Creating a dictionary with dictionary comprehension
Suppose we have a list of names and we want to create a dictionary using dictionary comprehension where the names are the keys and their lengths are the values.
# Python program to create a dictionary using dictionary comprehension. # Creating a list of elements of string type. names = ['Alice', 'Bob', 'Saanvi', 'Mahika'] # This statement creates a dictionary containing names as keys and their corresponding lengths as values. dict = {name: len(name) for name in names} print(dict)
Output: {'Alice': 5, 'Bob': 3, 'Saanvi': 6, 'Mahika': 6}
In this example code, we have created a list of names. The dictionary comprehension {name: len(name) for name in names} generates a dictionary where the names are the keys, and the corresponding values are the lengths of the names. Finally, we have stored the obtained resulting dictionary into a variable dict.
The above code is equivalent to:
# Creating a list of elements of string type. names = ['Alice', 'Bob', 'Saanvi', 'Mahika'] # Creating an empty dictionary. dict = {} for name in names: dict[name] = len(name) print(dict)
In this code, we have created an empty dictionary named dict. We have iterated over each name in the names list using a for loop. Inside the loop, we have assigned the length of each name as the value corresponding to the name key in the dict dictionary. Finally, we have printed the resulting dictionary, which will give us the same result as before.
Example 2: Squaring values in a dictionary
# Python program to create a dictionary using dictionary comprehension. # Creating a dictionary. org_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} # This statement will square the values and store the result in the new dictionary. sq_dict = {key: value**2 for key, value in org_dict.items()} # Displaying the result. print(sq_dict)
Output: {'a': 1, 'b': 4, 'c': 9, 'd': 16, 'e': 25}
In this example, we have an original dictionary org_dict with keys and values. The dictionary comprehension {key: value**2 for key, value in org_dict.items()} creates a new dictionary named sq_dict, where each value in org_dict is squared and assigned as the value for the corresponding key in sq_dict.
Within dictionary comprehension, we have used the items() method that allows us to access both the keys and values of the original dictionary simultaneously during the dictionary comprehension process.
Example 3: Swapping keys and values in a dictionary
# Python program to swap keys and values in a dictionary using dictionary comprehension. # Creating a dictionary. org_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4} # This statement swapped keys and values. swapped_dict = {value: key for key, value in org_dict.items()} # Displaying the result. print(swapped_dict)
Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Example 4: Creating a dictionary from two lists
# Python program to create a dictionary from two lists using dictionary comprehension. # Creating two lists. keys = [1, 2, 3, 4] values = ["one", "two", "three", "four"] # This statement creates a dictionary from two lists containing first lists as keys and second list as values. combined_dict = {key: value for key, value in zip(keys, values)} print(combined_dict)
Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Example 5: Creating a dictionary from a list of tuples
# Python program to create a dictionary from a list of tuples using dictionary comprehension. # Creating a list of tuples. tuple_list = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] # This statement creates a dictionary from a list of tuples. dict_from_tuples = {key: value for key, value in tuple_list} print(dict_from_tuples)
Output: {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Example 6: Extracting a subset of dictionary keys
# Python program to extract a subset of dictionary keys using dictionary comprehension. # Creating a dictionary. org_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} # This statement creates a new dictionary from a subset of existing dictionary keys. subset_dict = {key: org_dict[key] for key in ['a', 'c', 'e']} print(subset_dict)
Output: {'a': 1, 'c': 3, 'e': 5}
Example 7: Applying a function to dictionary values
# Python program to apply function to dictionary values within dictionary comprehension. import math org_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4} transformed_dict = {key: math.sqrt(value) for key, value in org_dict.items()} print(transformed_dict)
Output: {'a': 1.0, 'b': 1.4142135623730951, 'c': 1.7320508075688772, 'd': 2.0}
Example 8: Converting a dictionary into string representation
# Python program to convert a dictionary into string representation with dictionary comprehension. org_dict = {'a': 1, 'b': 2, 'c': 3, 'e': 4} str_dict = {str(key): str(value) for key, value in org_dict.items()} print(str_dict)
Output: {'a': '1', 'b': '2', 'c': '3', 'e': '4'}
Example 9: Creating a dictionary with a default value.
# Python program to create a dictionary with a default value with dictionary comprehension. # Creating a list of keys. keys = ['a', 'b', 'c', 'd'] default_value = 5 default_dict = {key: default_value for key in keys} print(default_dict)
Output: {'a': 5, 'b': 5, 'c': 5, 'd': 5}
Filtering Data with Dictionary Comprehension
We can also use dictionary comprehension to filter data based on certain conditions. Let’s say we have a dictionary of students and their scores. We want to create a new dictionary that only includes the students who scored above a certain threshold.
Example 10: Filtering dictionary items based on a condition
# Python program to filter data using dictionary comprehension. # Creating a dictionary of five entries. st_dict = {'Alice': 80, 'Bob': 75, 'Mahika': 90, 'Deep': 85, 'Mark': 72} # This statement will filter data based on the specified condition. top_students = {name: score for name, score in st_dict.items() if score > 80} # Displaying the resulted dictionary. print(top_students)
Output: {'Mahika': 90, 'Deep': 85}
Only two students, “Mahika” and “Deep” with a score of 90 and 85, met the condition. Hence, only two students have included in the new dictionary.
Example 11:
# Python program to filter and transform dictionary values using dictionary comprehension. # Creating a dictionary. org_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # This statement filters and transforms dictionary values. filtered_dict = {key: value * 3 for key, value in org_dict.items() if value > 2} print(filtered_dict)
Output: {'c': 9, 'd': 12}
Modifying Values with Dictionary Comprehension
In Python, dictionary comprehension also allows us to modify or update values of an existing dictionary. Let us consider a scenario where we have a dictionary for some product prices. We want to apply a discount of 20% to all the prices of products. Look at the example code below for it.
Example 12:
# Python program to modify data using dictionary comprehension. # Creating a dictionary of four entries. fr_prices = {'apple': 2.90, 'banana': 1.99, 'orange': 0.99, 'Mango': 3.99} # This statement will discount 20% of all prices. dis_prices = {product: price * 0.8 for product, price in fr_prices.items()} # Displaying the resulting discounted prices on the console. print(dis_prices)
Output: {'apple': 2.32, 'banana': 1.592, 'orange': 0.792, 'Mango': 3.192}
By multiplying each price by 0.8, we have reduced the prices by 20% and obtained the new dictionary.
Conditional Statements in Dictionary Comprehension
In Python, we can also incorporate conditional statements into the dictionary comprehension to include only certain elements that meet specific conditions.
Let us say we have a list of integer numbers. With dictionary comprehension, we will create a new dictionary where keys are numbers and values will show whether the number is even or odd. Look at the below example code for it.
Example 13:
# Python program to use conditional statement into dictionary comprehension. # Creating a list of seven numbers. nums = [1, 2, 3, 4, 5, 6, 7] even_odd = {num: 'even' if num % 2 == 0 else 'odd' for num in nums} print(even_odd)
Output: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd'}
In this example, we have used the conditional statement into dictionary comprehension that tests if each number is divisible by 2. If is it, the value is set to ‘even’, else ‘odd’.
Real-world Examples of Dictionary Comprehension
Python dictionary comprehension finds applications in various real-world scenarios. Here are a few examples:
- Data preprocessing and transformation tasks.
- Mapping and converting data from one format to another.
- Filtering and extracting specific information from data structures.
- Building lookup tables and dictionaries for efficient data access.
- Simplify the code by reducing the number of lines and improving readability.
Best Practices and Tips for using Dictionary Comprehension
While using dictionary comprehension in Python, you must keep the following best practices and tips in mind:
- Use descriptive variable names to enhance code readability.
- Split up complex comprehension expressions into multiple lines for clarity.
- Ensure the uniqueness of keys to avoid overwriting values.
- Use conditional statements to filter and transform data.
- Test the dictionary comprehension on smaller data sets before applying it to larger ones.
- Try to comment on your code to explain complex comprehensions and improve maintainability.
Frequently Asked Questions on Dictionary Comprehension
Q1: What is dictionary comprehension in Python?
A: Dictionary comprehension is a concise and efficient method to create a dictionary in Python. It creates a dictionary in a single line of code by defining key-value pairs based on an iterable, such as a list.
Q2: How does dictionary comprehension work in Python?
A: Dictionary comprehension works by iterating over elements of an iterable object and defining key-value pairs using a specific syntax. The resulting dictionary is generated by evaluating the output expression for each element in the iterable.
Q3: Is it possible to nest multiple levels of dictionary comprehension?
A: Yes, it is possible to nest multiple levels of dictionary comprehension to create dictionaries with deeper levels of nesting. It is especially useful while working with complex data structures.
Q4: Can we use dictionary comprehension with dictionaries that have non-unique keys?
A: Dictionary comprehension needs unique keys to avoid overwriting values. If the original data contains non-unique keys, we may need to preprocess or transform the data to ensure the uniqueness of keys before using dictionary comprehension.
Q5: Is it possible to modify an existing dictionary using dictionary comprehension?
A: Yes, we can use dictionary comprehension to modify or update the values of an existing dictionary by iterating over its key-value pairs and applying transformations or filters as needed.
Dictionary comprehension is a powerful technique in Python that allows us to make dictionaries in Python with ease and simplicity. We can reduce multiple lines of code by using it in the python program and improve code readability, making our programs more concise and easier to understand. It provides a convenient method to perform data transformations, filtering, and mapping operations on iterable data structures.
Dictionary comprehension is a versatile feature in Python. Therefore, it finds applications in various domains, including data analysis, web scraping, configuration settings, and natural language processing. It simplifies complex data manipulations and allows for the creation of lookup tables, data preprocessing, and JSON manipulation.
Hope that you will have understood the basic points of dictionary comprehension and practiced all example programs.
Thanks for reading!!!