Python Dict Comprehension(with examples)

Python Dict Comprehension

Hello Techies,

This tutorial is based on Python Dict Comprehension. In this blog, you will learn How to use the Python Dict Comprehension with the help of multiple examples.

Below are the points we are covering in this blog:

  • Python Dictionary
  • Python Dict Comprehension
  • Dictionary comprehension vs for loop
  • Nested Dictionary comprehension in Python
  • Dict comprehension conditional
  • Examples of Dict comprehension

Python Dictionary

  • The dictionary represents a group of elements in the form of a key-value pair.
  • Dictionary is an unordered collection.
  • Dictionaries are mutable that means we can modify its element.
  • Can declare a dictionary using square brackets {}.
  • Example: data = {‘test1’: 1, ‘test2’: 2, ‘test3’: 3, ‘test4’: 4}
data = {'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4}
print(data)
{'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4}

Python Dict Comprehension

Python Dict comprehension is a way of converting one dictionary into another. During this conversion, items from the original dictionary can be conditionally added to the new dictionary and each item can be converted as needed.

Python Dict comprehension is a concise way to build a dictionary. Using Dict comprehension we can access dictionary key-value pair.

Let’s see how to use Python dictionary comprehension.

The general Syntax of Python dictionary comprehension

dict_var = {key:value for (key,value) in dict.items()}

Let’s see simple example of Python Dictionary comprehension.

dict1 = {'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4}
result = {k:v+2 for (k, v) in dict1.items()}
print(result)

Output:

{'test1': 3, 'test2': 4, 'test3': 5, 'test4': 6}

In the above dictionary comprehension code, you create a new dictionary result from dict1 by simply adding 2 to each of its values.


Dictionary comprehension vs for loop

Suppose, if you want to iterate any sequence Dictionary, the first thing on your mind is the for loop.

Let’s check one example, how to use a for loop for iteration.

dict1 = {'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4}
result = {}
for key, value in dict1.items():
    result.update({key: value * 2})
print(result)

Output:

{'test1': 2, 'test2': 4, 'test3': 6, 'test4': 8}

Dictionary comprehension can be used to substitute for loop. However, not all for loops can be written as Dict Comprehension, but all Dict Comprehension can be written with a for loop.

Let’s check the above code using the dict comprehension in one line.

result = {k: v*2 for (k, v) in {'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4}.items()}
print(result)

Output:

{'test1': 2, 'test2': 4, 'test3': 6, 'test4': 8}

Nested Dictionary comprehension in Python

The nested Dict is a dictionary within the dictionary. The nested dictionary comprehension is the same as the nested for loop.

First, we will check Nested for loop example.

dict = {}
for k1 in range(2, 5):
    dict[k1] = {}
    for k2 in range(1, 6):
        dict[k1][k2] = k1 + k2
print(dict)

Output:

{2: {1: 3, 2: 4, 3 5, 4: 6, 5: 7}, 3: {1: 4, 2: 5, 3: 6, 4: 7, 5: 8}, 4: {1: 5, 2: 6, 3: 7, 4: 8, 5: 9}}

Using Dict comprehension

dictionary = {k1: {k2: k1 + k2 for k2 in range(1, 6)} for k1 in range(2, 5)}
print(dictionary)

Output:

{2: {1: 3, 2: 4, 3 5, 4: 6, 5: 7}, 3: {1: 4, 2: 5, 3: 6, 4: 7, 5: 8}, 4: {1: 5, 2: 6, 3: 7, 4: 8, 5: 9}}

Dict comprehension conditional

We can include several conditions in the Dict comprehension. Let us examine some examples of how to use conditions in Dict comprehension.

Dict comprehension if

Example: How to use if condition in the dictionary in Python?

original_dict = {'john': 38, 'mac': 48, 'robbert': 57, 'rock': 33}

result = {k: v for (k, v) in original_dict.items() if v > 45}
print(result)

Output:

{'mac': 48, 'robbert': 57}

Python Dict comprehension multiple if

Example: How to use multiple if condition in the dictionary in Python?

original_dict = {'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4, 'test5': 5, 'test6': 6}

result = dict1_doubleCond = {k: v for (k, v) in original_dict.items() if v > 2 if v % 2 == 0}
print(result)

Output:

{'test4': 4, 'test6': 6}

Python Dict comprehension if-else

Example: How to use the if-else condition in the dictionary in Python?

original_dict = {'test1': 1, 'test2': 2, 'test3': 3, 'test4': 4, 'test5': 5, 'test6': 6}

# Identify odd and even entries
result = {k: ('even' if v % 2 == 0 else 'odd') for (k, v) in original_dict.items()}
print(result)

Output:

{'test1': 'odd', 'test2': 'even', 'test3': 'odd', 'test4': 'even', 'test5': 'odd', 'test6': 'even'}

Examples of Dict comprehension

Sorting a Dictionary using Dict comprehension

Example: Sort by keys in ascending order

original_dict = {"a": 5, "b": 6, "d": 3, "c": 2}
result = {k: d[k] for k in sorted(d)}

Output:

Original Dict {'a': 5, 'b': 6, 'd': 3, 'c': 2}
Result: {'a': 5, 'b': 6, 'c': 2, 'd': 3}

Modify dictionary using Dict comprehensions without creating a new dictionary

original_dict = {'test-02': 'abc', 'test-03': 'xyz', 'test-01': 'abc', 'test-04': 'xyz', 'test-05': 'abc'}
print("Original Dict", original_dict)
original_dict.update({i: 'result-test' for i in original_dict if i[-2:] in ('02', '05')})
print("Result:", original_dict)

Output:

Original Dict {'test-02': 'abc', 'test-03': 'xyz', 'test-01': 'abc', 'test-04': 'xyz', 'test-05': 'abc'}
Result: {'test-02': 'result-test', 'test-03': 'xyz', 'test-01': 'abc', 'test-04': 'xyz', 'test-05': 'result-test'}

I hope you have understood the concept of dict comprehension for more information about data structures check the official site.

Leave a Comment