Dictionary Comprehension in Python

There may be situations while working with dictionaries in python where we need to create a new dictionary from another dictionary by including some items from the dictionary based on a condition or we want to create a new dictionary having keys and values following a specific condition. We may do it by manually checking the dictionary items one by one using a for loop and adding them to the new dictionary. In this tutorial, we will see how we can achieve the same result using a concise construct called dictionary comprehension in python.

Also Read: Java Program to Print Stair Case Number Pattern

What is dictionary comprehension?

Just like list comprehension is a way to create lists from other lists, dictionary comprehension is a way to create a python dictionary from another dictionary or from any other iterable. We can create new dictionaries with the same elements as the original dictionary based on conditional statements or we can transform the items in the dictionary according to our needs. We can either modify the keys or the values or both key and value of items in the dictionary while creating a new dictionary using dictionary comprehension.

While creating a dictionary using dictionary comprehension, we have to get a key-value pair either from any dictionary or from any other iterable.Syntax for dictionary comprehension can be as follows.

myDict={key:value for var in iterable}

While creating a dictionary from a list or tuple using the elements of list or tuple as keys and values derived from the elements, we can use the following syntax.

myDict={key:value for var in list_name}
myDict={key:value for var in tuple_name}

While creating a dictionary from another dictionary, we can use the following syntax.

myDict={key:value for (key,value) in dict_name.items()}

How to use dictionary comprehension?

We can create a dictionary by using elements from a list. Suppose we want to create a python dictionary with elements of the list as keys and values then we can do it as follows.

myList=[1,2,3,4]
myDict={x:x for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)

Output:

List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 2, 3: 3, 4: 4}

In the output, we can see that the created dictionary has keys and values same as that of elements in the given list.

We can also modify the elements of the list before adding them to dictionary while creating a new dictionary. Suppose we want to create a dictionary having elements of the list as keys and their squares as values the we can do it as follows.

myList=[1,2,3,4]
myDict={x:x**2 for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)

Output:

List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}

In the output, we can see that the created dictionary has elements of the list as keys and their squares as values.

We can also selectively use items from lists based on conditions while creating the dictionary. Suppose we want to create a dictionary having elements of the list which are even as keys and their squares as values the we can do it as follows.

myList=[1,2,3,4]
myDict={x:x**2 for x in myList if x%2==0}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)

Output:

List is:
[1, 2, 3, 4]
Created dictionary is:
{2: 4, 4: 16}

In the output, we can see that only those elements of the list which are even numbers has been used as keys in the created dictionary and their squares are the respective values of the keys of the dictionary.

We can also create a dictionary  by using items from another dictionary. For this we can extract key value pairs using items() method from the original dictionary. items() method gives a list of tuples as (key,value) pairs which we can use to create a new dictionary.

For example, we can create a new dictionary exactly as a given dictionary using dictionary comprehension as follows.

myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value for (key,value) in myDict.items()}
print("New dictionary is:")
print(newDict)

Output:

Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{1: 1, 2: 2, 3: 3, 4: 4}

In the output, we can see that the new dictionary is containing the same key value pairs as original dictionary.

We can also modify the dictionary items from the original dictionary before including them to the new dictionary. For example, the following program modifies the values of the items before adding them into new dictionary.

myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items()}
print("New dictionary is:")
print(newDict)

Output:

Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}

In the output, we can see that the keys of the new dictionary as same as original dictionary but the values of the items in new dictionary as squares of values of the item in the original dictionary.

We can also use conditions to selectively choose items from the older dictionary using conditions  while creating a new dictionary.

For example, the following program filters out the items whose keys are odd numbers and considers only those items to add in new dictionary in which the keys are even numbers. It further squares the values of those items before adding them to new dictionary.

myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items() if key%2==0}
print("New dictionary is:")
print(newDict)

Output:

Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{2: 4, 4: 16}

In the output, we can see that the key value pairs in new dictionary have only even numbers as their keys and their squares as respective values.

Conclusion

In this article, we have seen what dictionary comprehension is and how to use them to create new dictionaries. Dictionary comprehensions can be used to replace for loops while creating dictionaries and make the source code more concise  and increase the readability of the code when complex conditions are not used. In cases when we use complex conditional statements inside dictionary comprehension, it may decrease the readability of the source code. The execution of the code may also slow down and the program will require more memory space. So, while handling complex conditional statements to create dictionaries, it is better to use for loops instead of dictionary comprehensions. Stay tuned for more informative articles.

Leave a Reply

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