A dictionary in Python an unordered collection of data values. Similar to a dictionary in the real world with values (definitions) mapped to a specific key (words).
Dictionary comprehension is one way to create a dictionary in Python. It creates a dictionary by merging two sets of data which are in the form of either lists or arrays.
The data of one of the two lists/arrays will act as the keys of the dictionary while the data of the second list/array will act as the values. Each key acts as a unique identifier for each value, hence the size of both lists/arrays should be the same.
There are two types of merging. Simple and Conditional merging.
Simple merging is merging or combining two lists without any restrictions. In other words, it is the unconditional merging.
The general syntax is as follows:
Iterable is a collection of objects.
As the name suggests conditional merging is merging the two data sets based on a specific condition. A value is placed against its key only if it meets the condition. Otherwise, it will not be catered.
The general syntax is as follows:
Suppose we want to create a dictionary of a number with its square if it is divisible by 4. Following diagram explains this conditional merging.
Lets try to understand the parameters mentioned above.
The dictionary comprehension basically consists of four parameters.
Output expression: Defines the output of the dictionary
List/Input: Defines the list which is to be traversed.There can be two or more lists to be traversed.
Conditional/predicate: Defines a condition on variable x. This is an optional parameter.
NewDictionary: Saves the result of list expression depending on the condition and creates a tuple.
The following example runs for the college’s data base and uses simple merging. Imagine that there is a college’s database storing lots of data. For example student’s address, grades, section, fees, roll number and so on. Now we need to identify each student uniquely and create a new dictionary which stores all students only. Our decision simply depends on two questions:
Here we will choose roll numbers as key and names as value because roll numbers are unique and names could be repetitive.
So Alex’s roll number is 122 so the tuple will look like 122: Alex. This will be better explained once you try the code attached below.
zip() is our iterable and its purpose is to map the similar values of multiple containers so that they can be used as a single entity.
rollNumbers =[122,233,353,456]names = ['alex','bob','can', 'don']NewDictionary={ i:j for (i,j) in zip (rollNumbers,names)}print(NewDictionary)
The following code uses conditional merging and stores only the square of those numbers existing in the list which are divisible by 4.
The code below uses ‘x**’ operator to take the square of the variable x. You may use any other function to calculate the square.
values=[1,2,3,4,5,6,7,8,9,10]NewDictionary = {x: x**2 for x in values if x**2 % 4 == 0}print(NewDictionary)