Dictionaries are powerful built-in data structures in Python that store data in pairs.
Eg: dict1={0: 'Fruit' , 1: 'Vegetable'}
For more info on What is a Dictionary do check the Wikipedia page
Comprehension is nothing but a process of creating a new sequence from the existing sequence. And hence, Dictionary Comprehension is an elegant way of creating new dictionaries, sequences, or collections from existing dictionaries.
Your code will be more expressive and hence simpler to comprehend if you have good list comprehension. When it comes to comprehensions, the idea is not to make them so complicated that trying to figure out what they’re doing makes your head spin. Keeping the “simple to read” concept alive.
It can be used as a substitute for “for”
loops and “lambda”
functions. Although not every “for” loop can be expressed as a dictionary comprehension, every dictionary comprehension can be written using a for a loop.
In this blog, we’ll learn how dictionary comprehensions work in Python by coding some simple examples.
What is a dictionary in Python?
Dictionaries are Python’s version of an associative array, which is more often known as a data structure that is made up of a set of key-value pairs. They are expressed in curly brackets ({}), including key-value pairs separated by commas (,). A colon (:) which separates each key from its value. And each key-value combination corresponds to a certain value.
Here’s the syntax:
my_dict = {"key1":<value1>,"key2":<value2>,"key3":<value3>,"key4":<value4>}
Some points to note:
- All items in the dictionary are enclosed within a pair of curly braces{}.
- Each item in a dictionary that is inside the curly braces{} and between the comma(,) is called a key-value pair.
In the above example,
- The dictionary my_dict contains 4 key-value pairs (items).
- “key1” – “key4” are the 4 keys.
- You can use my_dict[“key1”] to access <value1>, my_dict[“key2”] to access <value2>, and so on.
Let’s study Dictionary Comprehension now that we know what a Python dictionary is.
How to Use Dictionary Comprehension to Create a Python Dictionary
As previously stated, Dictionary Comprehension is nothing but an elegant way of creating new dictionaries, sequences, or collections from existing dictionaries. Let’s use dictionary comprehension to generate a Python dictionary from an iterable, such as a list or a tuple, in this part.
If we choose to produce either the keys or the values, we may construct a new Python dictionary with only one iterable. When generating the values, the items in the iterable can be used as keys and vice versa.
Let’s have a look at the Dictionary Comprehension Syntax :
<dict_name> = {<new_key>:<new_value> for <item> in <iterable>}
- {} indicates that we’re populating a dictionary.
- For each item in the iterable, we generate a key-value pair in the dictionary.
Example 1
Suppose you want to create a dictionary that contains a key as the number and the value is multiplied by 2 till the range of 9. We should be getting an output like this {1 : 1, 2 : 4 , 3 : 6, …, 9 : 18 }. We have we can derive the formula num: num *2, now how can we create this dictionary?
Let’s first see this with traditional way then we will see with python dictionary comprehension
Traditional way:
Input:
dict1={} for n in range (10): dict1[n]= n*2 print(dict1)
Output:
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Here, python will first run the loop in n starting from 1 and derive the expression which is dict1[n]=n*2, and give the first output and it will keep running until we get the output for 9.
Dictionary Comprehension :
Input:
dict2={n:n*2 for n in range(10)} print(dict2)
Output:
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Here first it will execute the for loop and then the expression which is num:num*2
So, it will go to 1 which will be our key, and 1*1 which is a pair Then it will go to 2 Then 3 and so on up to 9
Here, we tried creating a dictionary using python dictionary comprehension.
Now, which method do you think is easy and simple? Of course, the second one is because it saves our time and it makes the code look clean.
How to Use Conditionals in Dictionary Comprehension
You often have to use conditions to find a solution while writing codes. By adding conditions to python dictionary comprehension if and else, we may further personalize it. Let’s check out how you can add conditionals into dictionary comprehension and make it more efficient.
If Condition
Example 2
We can use the same previous problem which is creating a dictionary that contains a key as the number and the value is multiplied by 2 till the range of 9 but now we want key to be an even number. So we need to add an “if” statement to find the solution. We should be getting an output like this {0: 0, 2: 4, 4: 8, 6: 12, 8: 16} where {0 = key 1 : 0 = value 1, 2 = key 2 : 4 = value 2, 4 = key 3 : 8 = value 3, 6 = key 4 : 12 = value 4, 8 = key 5 : 16 = value 5}
Traditional way:
Input:
dict1={} for n in range (10): if n%2==0: dict1[n]= n*2 print(dict1)
Output:
{0: 0, 2: 4, 4: 8, 6: 12, 8: 16}
Here, python will first run the loop in n starting from 0 and derive the expression which is dict1[n]=n*2, then it will check whether the number is even or odd and if it is even then it will give the first output and it will keep running until we get the output for the last even number which is 8.
Now let’s check the dictionary comprehension method.
Dictionary Comprehension:
Input:
dict2={n:n*2 for n in range(10) if n%2==0} print(dict2)
Output:
{0: 0, 2: 4, 4: 8, 6: 12, 8: 16}
Here first it will execute the for loop and then the expression which is num:num*2. So it will go to all the numbers from 0 to 9 and check for the even numbers and execute all the even numbers according to num:num*2. This is done by using Python Dictionary Comprehension which not only saved our time but also kept the code very minimal and simple.
And similarly, we can even add if-else statements if required to solve a problem.
If Else Condition
Now, let us add else statement as well and run the code. We will add a condition that if the key number turns out to be odd then the value that we get should be “invalid” in the previous example. First using the “for” loop and then by using Python Dictionary Comprehension
Example 3
Traditional way:
f n%2==0: dict1[n]= n*2 else: dict1[n]= "Invalid" print(dict1)
Output:
{0: 0, 1: 'Invalid', 2: 4, 3: 'Invalid', 4: 8, 5: 'Invalid', 6: 12, 7: 'Invalid', 8: 16, 9: 'Invalid'}
Using a for loop, python will run the loop check the conditions until it is satisfied, and assign the key-value pairs as mentioned here but in dictionary comprehension, it is much easier.
Dictionary Comprehension:
dict2={n:(n*2 if n%2==0 else "Invalid") for n in range(10)} print(dict2)
Output:
{0: 0, 1: 'Invalid', 2: 4, 3: 'Invalid', 4: 8, 5: 'Invalid', 6: 12, 7: 'Invalid', 8: 16, 9: 'Invalid'
Nested Dictionary Comprehension
To construct nested dictionaries, we may add dictionary comprehensions to dictionary comprehensions. Nesting is a programming technique in which data is structured in layers or items are nested within other objects of the same kind. A nested ‘if’ structure, which is an if condition within another if condition, is probably something you’ve encountered before.
In the same way that dictionaries may be nested, so can their comprehensions. Let’s have a look using the method that we use regularly and then by using Python Dictionary Comprehension.
You may be also interested in: Top programming mistakes
Example 4
As now we know what nesting is, We’re going to add one more condition that is the key should be divisible by 2 first, and then it should be divisible by 3.
Traditional way:
Input:
nesteddict1={} for n in range (10): if n%2==0: if n%3==0: nesteddict1[n]= n*2 print(nesteddict1)
Output:
{0: 0, 6: 12}
Dictionary Comprehension:
Input:
nesteddict2={n:n*2 for n in range(10) if n%2==0 if n%3==0} print(nesteddict2)
Output:
{0: 0, 6: 12}
This is an example of a nested dictionary using Python Dictionary Comprehension
In every case, you will witness that Python Dictionary Comprehension works smoothly and fast.
Advantages of Using Dictionary Comprehension
- It saves our time when it comes to dealing with dictionaries.
- Using this, we can shorten our code and keep the logic intact.
Conclusion
You’ve successfully completed this tutorial. You’ve learned – What is a Dictionary, Dictionary Comprehension, and how to use Dictionary Comprehension to generate Python dictionaries from sequences and collections like one iterable, two iterables, and an existing dictionary by filtering through the elements using conditions. Now you’re eligible to handle a python dictionary comprehension. Keep practicing python and keep learning!
Data Scientist with 3+ years of experience in building data-intensive applications in diverse industries. Proficient in predictive modeling, computer vision, natural language processing, data visualization etc. Aside from being a data scientist, I am also a blogger and photographer.