/    /  DBMS – Dictionary Comprehension in Python

Dictionary Comprehension in Python

 

Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets.

 

Unlike sequences, which are iterables that support accessing of elements using integer indexing, dictionaries are indexed by keys. Dictionaries are generally optimized to retrieve values when the key is known. Values (definitions) mapped to a specific key (words) similar to that of a dictionary in the real world.

 

Here are some of the basic functions to access the elements in a dictionary.

 

Accessing Keys using dict_name.keys()

 

Example:

Onedict = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
Onedict.keys()

 

Output:

 

Accessing values using dict_name.values()

 

Example:

Onedict = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
Onedict.values()

 

Output:

 

Accessing all the items using dict_name.items()

 

Example:

Onedict = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
Onedict.items()

 

Output:

 

Dictionary comprehension is one of the most efficient ways to create a dictionary in Python. A dictionary is created by merging two sets of data which are in the form of either lists or arrays. The data from one of the two lists/arrays will be the keys of the dictionary while the data from the second list/array will be the values for our new dictionary. Every key is like a unique identifier for every respective value, So we must make sure that the size of both lists/arrays must be the same.

 

General Syntax: {key: value for (key, value) in iterable}

 

Iterable is a collection of objects.

 

Another way of doing it is using the below syntax.

NewDictionary = key:value for list in iterable conditional condition

 

key:value is the output expression and this defines the output of the dictionary

 

List/Input is the list that is to be traversed. We can have two or more lists.

 

Conditional is an optional parameter. This can be an if, if-else or nested if statement.

 

NewDictionary is a variable that saves the result of the list expression depending on the condition and it creates a tuple.

 

Let us take an example where our task is to find the squares of the first 8 numbers. We can achieve this using a for loop

 

Example:

Squares= dict()
for num in range(1, 9):
   squares[num] = num*num
print(Squares)

 

Output:

Let us now try to optimize this code using dictionary comprehension.

 

Example:

Squares = {num: num*num for num in range(1, 9)}
print(Squares)

 

Output:

 

We’ll now try to compare this line of code with the parameters discussed.

num:num*num is the output expression.

num is our list/input.

range(1,9) is our iterable.

Squares is the NewDictionary.

 

Why Dictionary Comprehension?

  1.     It’s a great alternative to for loops

 

Note: We can’t write or replace all for loops using dictionary comprehension, but most of the dictionary comprehensions can be written using a for loop.

 

Example:

data = range(10)
dict_wid_for = {}

for n in data:
   if n%2==0:
      dict_wid-for[n[ = n**2

print(dict_wid_for)

 

Output:

 

Example:

data = range(10)
dict_wid_comp= {n:n**2 for n in data if n%2 == 0}

print(dict_wid_comp)

 

Output:

 

  1.     As an alternative for lambda functions

Lambda functions are small anonymous functions that don’t have a name. These functions are only needed where they have been created. We often use filter(), map() and reduce() functions along with the Lambda functions and using these the code would be too lengthy.

 

Using Conditionals in Dictionary Comprehension

if condition:

We have a dictionary named Onedict and our task is to print a dictionary on the condition that the value is greater than 2. We make use of if condition here. 

 

Example:

Onedict = {'a': 0, 'b': 2, 'c': 4, 'd': 6, 'e': 8}

dict_wid_if = {x:y for (x,y) in Onedict.items() if y>2}

print(dict_wid_if)

 

Output:

 

Multiple if conditions:

Let’s consider the same Dictionary Onedict and now our task is to create a dictionary whose values are greater than 2 and also divisible by 4. We make use of two if conditions here.

 

Example:

Onedict = {'a': 0, 'b': 2, 'c': 4, 'd': 6, 'e': 8}
dict_wid_mulif = {x:y for (x,y) in Onedict.items() if y>2 if y&4 == 0}
print(dict_wid_mulif)

 

Output:

 

if-else condition:

Let’s consider another dictionary named Twodict with the values mentioned below and now, our task is to make a dictionary whose values must be either even or odd based on the key value. We make use of an if-else condition here.

 

Example:

Twodict = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

dict_wid_ifelse = {x:('even' if y%2==0 else 'odd') for (x,y) in Twodict.items()}

print(dict_wid_ifelse)

 

Output:

Note: The usage of conditionals in Dictionary Comprehension is optional.