Dictionary Comprehension in Python
Dictionary Comprehension in Python

Dictionary Comprehension in Python

A Python Dictionary is a data structure that stores values in the form of key-value pairs. It has a variety of applications in Python programming. In addition to various properties of a dictionary, Python provides an effective method known as Dictionary Comprehension. Dictionary comprehension is a method of creating a Dictionary from another iterable object in Python. It is very much similar to List comprehension in Python. We use it as a concise method to create new dictionaries.

How to define Dictionary Comprehension in Python?

Dictionary comprehensions are defined inside curly braces using the following syntax.

dictionary = {key: value for member in iterable if condition}

The above syntax includes three elements: a key-value pair, an iterable, and a condition.

Here,

  • The iterable is the existing iterable object.
  • The member represents an element of iterable.
  • The key and value represent the values derived from elements of the iterable.
  • The condition is used on key, value, or member to filter values while creating the dictionary.

Let’s see an example to understand Dictionary comprehension. We will be creating a dictionary string_length where each key will be the element of string_list and its value will be the length of the string. Here, we will only consider even-length strings.

# list of strings
string_list = ['python', 'data', 'science', 'machine', 'learning']
print("List of strings:", string_list)

# creating dictionary using dictionary comprehension 
string_length = {k: len(k) for k in string_list if len(k) % 2 == 0}
print("Dictionary:", string_length)

Output:

List of strings: ['python', 'data', 'science', 'machine', 'learning']
Dictionary: {'python': 6, 'data': 4, 'learning': 8}

In the above example, we have created a dictionary from the elements of a list. We have specified the key as k and its value as len(k). Here, iterable is the list string_list and condition is [if len(k) % 2 == 0].

When and why should we use Dictionary Comprehension in Python?

We should use dictionary comprehension whenever we want to create a dictionary based on another sequence of objects. It provides a simple method to create new dictionaries from existing dictionaries or iterable ones. Now the question is why use Dictionary comprehension instead of the traditional approach?

We know that with the help of Iteration, we can iterate through all the key-value pairs of a dictionary. This is the traditional approach to accessing items in a dictionary. We generally use for loop for iteration.

Now we will see a few examples in which we will be creating dictionaries using both traditional approach and dictionary comprehension. Then we’ll try to figure out how comprehension proves to be more efficient than the normal iteration.

Example 1 – Given a dictionary of food items and their price. Create a new dictionary from the existing dictionary where the price of all the food items is increased by 15%.

Using the traditional approach (using for loop).

original_price = {'Toast': 30, 'Sandwich': 45, 'Coffee': 40, 'Bun': 15}
# initializing new dictionary
revised_price = {}
# using for loop
for (k, v) in original_price.items():
    revised_price[k] = v + v * 0.15

print("New dictionary:", revised_price)

Output:

New dictionary: {'Toast': 34.5, 'Sandwich': 51.75, 'Coffee': 46.0, 'Bun': 17.25}

Now we will perform the same task using dictionary comprehension.

original_price = {'Toast': 30, 'Sandwich': 45, 'Coffee': 40, 'Bun': 15}

# using dictionary comprehension
revised_price = {k:v + (v * 0.15) for (k,v) in original_price.items()}

print("New dictionary:", revised_price)

Output:

New dictionary: {'Toast': 34.5, 'Sandwich': 51.75, 'Coffee': 46.0, 'Bun': 17.25}
Example 2 – Given a dictionary representing the student’s name and marks. Create a dictionary that will represent the name and result of the student. If marks are more than 40 students are said to be ‘pass’ otherwise ‘fail’.

Using the traditional approach.

marks_dict = {'John': 87.5, 'Mark': 68.35, 'Dan': 38, 'George': 90.8, 'Emily': 31.65}

# initializing new dictionary
result = {}
# using for loop
for (name, marks) in marks_dict.items():
    if marks > 40:
        result[name] = 'pass'
    else:
        result[name] = 'fail'

print("Result:", result)

Output:

Result: {'John': 'pass', 'Mark': 'pass', 'Dan': 'fail', 'George': 'pass', 'Emily': 'fail'}

Using dictionary comprehension.

marks_dict = {'John': 87.5, 'Mark': 68.35, 'Dan': 38, 'George': 90.8, 'Emily': 31.65}

# using dictionary comprehension
result = {name: ('pass' if marks > 40 else 'fail') for (name, marks) in marks_dict.items()}

print("Result:", result)

Output:

Result: {'John': 'pass', 'Mark': 'pass', 'Dan': 'fail', 'George': 'pass', 'Emily': 'fail'}
Example 3 – Create a dictionary that contains cubes of all the integers less than 10 and whose cube is divisible by 4.

Using the traditional approach.

# initializing empty dictionary
cube_div_four = {}
# using for loop
for k in range(1, 10):
    if (k**3) % 4 == 0:
        cube_div_four[k] = k**3

print("Cube dictionary:", cube_div_four)

Output:

Cube dictionary: {2: 8, 4: 64, 6: 216, 8: 512}

Using dictionary comprehension.

# using dictionary comprehension
cubes = {k: k**3 for k in range(1, 10) if (k**3) % 4 == 0}
print("Cube dictionary:", cubes)

Output:

Cube dictionary: {2: 8, 4: 64, 6: 216, 8: 512}

From the three examples above, we can easily see the difference between the amount of code we used in both approaches.

In comparison to the traditional approach, the code in dictionary comprehension was much smaller, simpler, and more efficient. In the case of the traditional approach, we have first iterated over all the elements. After that, we used conditional statements to check conditions, and then we added key-value pairs to our dictionary. While in the case of Dictionary Comprehension, all this work was done in a single line of code. So, it is better to use comprehension in comparison with for loops.

What is Nested Dictionary Comprehension?

Nested Dictionary Comprehension refers to a dictionary comprehension within another dictionary comprehension. We use it to generate or create nested dictionaries i.e., a dictionary within a dictionary. In other words, we can say whenever we want to create a dictionary of dictionaries (2-D dictionaries), we use nested dictionary comprehensions.

Let’s take an example. We are creating a multiplication table (up to 5th multiple) for numbers from 2 to 5.

# multiplication table
multiplication_table = { k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 6)}

# printing multiplication table
print("Multiplication table:", multiplication_table)

Output:

Multiplication table: {2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}, 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}, 5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25}}

We will be doing the same task using for loop also.

# initializing outer dictionary 
multiplication_table = {}
for k1 in range(2, 6):
    # initializing inner dictionary
    multiplication_table[k1] = {}
    for k2 in range(1, 6):
        multiplication_table[k1][k2] = k1 * k2

print("Multiplication table:", multiplication_table)

Output:

Multiplication table: {2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}, 4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}, 5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25}}

So, we can clearly see the difference between the traditional approach and nested dictionary comprehensions. Therefore, using nested dictionary comprehensions, we were able to create nested dictionaries much more efficiently.

Conclusion

In this article, we have read about dictionary comprehensions, nested dictionary comprehensions, and their comparison with for loops. Dictionary comprehension is a more efficient way to define and construct lists based on existing Sequences. It requires much lesser code than the for loops.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply