Skip to content

Python dictionary comprehension

  • by

Dictionary comprehension is an elegant and concise way to create dictionaries from another dictionary. Or you can say transforming or creating one dictionary into another dictionary based on conditions.

A dictionary comprehension takes the form.

{key: value for (key, value) in iterable}
{key_expression: value_expression for item in iterable}

Here, key_expression and value_expression are expressions that define the key and value of each key-value pair, and iterable is the sequence of elements over which you want to iterate.

Python dictionary comprehension

A simple example code creates the dictionary with number-square key/value pair in the program using dictionary comprehension.

square_dict = {num: num*num for num in range(1, 11)}



Python dictionary comprehension

Make dict using two lists named keys and value.

keys = ['a','b','c','d','e']
values = [1,2,3,4,5]  
# but this line shows dict comprehension here  
myDict = { k:v for (k,v) in zip(keys, values)}  
# We can use below too
# myDict = dict(zip(keys, values))  
print (myDict)

Output: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5}

You can also make a dictionary from a list using comprehension.

myDict = {x: x**2 for x in [1,2,3,4,5]}
print (myDict)

If Conditional Dictionary Comprehension

This example below maps the numbers to their cubes that are not divisible by 4:

newdict = {x: x**3 for x in range(10) if x**3 % 4 == 0}

Output: {0: 0, 8: 512, 2: 8, 4: 64, 6: 216}

if-else Conditional Dictionary Comprehension

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}

res = {k: ('old' if v > 40 else 'young')
    for (k, v) in original_dict.items()}

Do comment if you have any doubts or suggestions on this Python comprehension topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *