Methods and Functions

Python Dictionary Comprehension

In Python, dictionaries are data types that allow us to store data in key/value pairs. In Python, a dictionary is an unsorted collection of data values. A dictionary in the programming language is just like in the actual world a dictionary having values (definitions) mapped to a certain key (words). Suppose we want to create a dictionary, we can do it either by adding single elements one at a time or we could use an iterator and the range() function to fill the values automatically. Learn Python dictionary comprehension here.

Example 1 –

                    

# Create a Dictionary for storing even numbers
my_dict = {}

my_dict[1] = 1
my_dict[2] = 4
my_dict[3] = 9
my_dict[4] = 16
my_dict[5] = 25

print('Squares of respective Keys are: ', my_dict)

Output –

                    

Squares of respective Keys are:  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Example 2 –

                    

# Create a dictionary for number and its square value
my_dict = {}

for i in range(1,6):
    my_dict[i] = i*i
print('Squares of respective Keys are: ', my_dict)

Output –

                    

Squares of respective Keys are:  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Both the above methods can be written in a more Pythonic way which will save you from having to write multiple lines of code and makes your code look tidy. This can be done by using the Python dictionary comprehension method. How? Let us learn it in this below article.

What is Dictionary Comprehension in Python?

In Python, Dictionary comprehension allows you to generate dictionaries in a Pythonic, clean, and easy-to-understand manner. With Python Dictionary Comprehension, we can use a single line of code to run a for loop on a dictionary.

Considering the above example for printing numbers as key and its square as its value using the Python dictionary comprehension method.

                    

my_dict = {i: i*i  for i in range(1,6)}

print('Squares of respective Keys are: ', my_dict)

Output –

                    

Squares of respective Keys are:  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Thus we have successfully created a dictionary in a single line of code using the python dictionary comprehension method.

Definition

  • Python dictionary comprehension method is used to create efficient dictionaries in a single line of code.

Python Dictionary Comprehension

Dictionary comprehension must be always written in a specific format. The syntax is mentioned below.

Syntax –

                    

dictionary = {key: value for vars in iterable}

where,

vars = can either be variables declared or (key, value) pair

iterable  = any object which we can loop over. E.g. list, tuple, string.

If we have 2 lists which we want to convert into a single dictionary, we can do it easily using the python dictionary comprehension method. Let us understand how by looking at the below example.

Example –

                    

# Python program to convert 2 lists into dict
num = [1, 2, 3, 4, 5]
cars = ['BMW', 'Ford', 'Audi', 'Tata', 'Ferrari']

# Python dictionary comprehension method
my_dict = {key:value for (key, value) in zip(num, cars)}   # we use zip function to add 2 lists into dict
print('My dictionary: ', my_dict)

Output –

                    

My dictionary:  {1: 'BMW', 2: 'Ford', 3: 'Audi', 4: 'Tata', 5: 'Ferrari'}

Let us understand the above dictionary comprehension statement by comparing it with our syntax.

Python dictionary comprehension

Dictionary comprehensions are a reversal of for loops. First, we define what our key-value pairs should be. Then we wrap everything in curly brackets using the same method we used for loop.

Using Dictionary Comprehension

One advantage of using the dictionary comprehension method is if we want to make changes or if we want to convert the values of a previously declared dictionary, we can do it with ease.

Example –

                    

# Item prices in Rs
price = {'Pen': 10, 'Book': 30, 'Eraser': 5, 'Crayons': 60}
rate = 0.5

new_price = {item: value*rate for (item, value) in price.items()}
print('New Prices are: ', new_price)

Output –

                    

New Prices are:  {'Pen': 5.0, 'Book': 15.0, 'Eraser': 2.5, 'Crayons': 30.0}

Conditionals in Dictionary Comprehension

Dictionary comprehension statements can be further customized by adding various conditional statements. Let us look at a few of them below,

  1. If conditional Dictionary comprehension

If condition can be added in the dictionary comprehension syntax. In the below program, we want items from the dictionary whose prices are greater than 30 Rs. This can be done as follows:

Example –

                    

# Item prices in Rs
item_price = {'Pen': 10, 'Book': 30, 'Eraser': 5, 'Crayons': 60, 'Craft Papers': 100, 'Writing Pad': 60, 'Pencil Box': 15}

sep_items = {k: v for (k, v) in item_price.items() if v > 30}
print('Items above Rs 30 are: ', sep_items)

Output –

                    

Items above Rs 30 are:  {'Crayons': 60, 'Craft Papers': 100, 'Writing Pad': 60}

We can also have multiple if conditions in the same line of dictionary comprehension syntax code.

Example –

                    

# Python program to illustrate multiple if statements in dict comprehension
car_rank = {'Ferrari': 1, 'Audi': 2, 'Porsche': 3, 'BMW': 4, 'Tata': 5, 'Jaguar': 6, 'Toyota': 7, 'Honda': 8, 'GM': 9, 'Land Rover': 10}

sep_rank = {k: v for (k, v) in car_rank.items() if v % 2 == 0  if v < 10}
print('Top Even ranking Car Brands below 10: ', sep_rank)

Output –

                    

Top Even ranking Car Brands below 10:  {'Audi': 2, 'BMW': 4, 'Jaguar': 6, 'Honda': 8}

  1. If-else conditional Dictionary comprehension

Here we create a separate new dictionary by using if else condition in the dictionary comprehension statement.

Example –

                    

# Python program to illustrate if-else statements in dict comprehension
age = {'Sam': 18, 'Trish': 23, 'Jim': 34, 'Arnold': 56, 'Jane': 68, 'Sean': 40, 'Mike': 35}

age_cat = {k: ('young' if v < 40 else 'old') for (k, v) in age.items()}
print('Categorized Young and Old people: ', age_cat)

Output –

                    

Categorized Young and Old people:  {'Sam': 'young', 'Trish': 'young', 'Jim': 'young', 'Arnold': 'old', 'Jane': 'old', 'Sean': 'old', 'Mike': 'young'}

Nested Dictionary Comprehension

Nesting is a programming technique in which data is structured in layers or items are nested within other objects of the same type. Just like a nesting of loops statements, we can nest dictionary comprehensions into dictionary comprehension.

Example –

                    

table = { k1: {k2: k1 * k2 for k2 in range(1, 5)} for k1 in range(2, 4)}
print(table)

Output –

                    

{2: {1: 2, 2: 4, 3: 6, 4: 8}, 3: {1: 3, 2: 6, 3: 9, 4: 12}}

We have created a multiplication table using nested dictionary comprehension.

If the above program was to be written using 2 for loops, it would have been –

                    

table = dict()

for k1 in range(2, 4):
    table[k1] = dict()
    for k2 in range(1, 5):
        table[k1][k2] = k1*k2
print(table)

And the output would have been the same. Nested dictionary comprehension saves coding time as well as makes the readability of the code pretty easy.

Removing a Selected Item from Dictionary

If there is a need of printing a new dictionary by removing certain key/value pairs from the old dictionary, we can do it using the dictionary comprehension method in Python.

Example –

                    

category = {'Electronics': 'TV', 'Electronics': 'Laptop', 'Clothing': 'Tshirt', 
           'Grocery': 'Vegetables', 'Toys': 'Remote Car', 'Electronics': 'Mobile'}

new_dict = {k:category[k] for k in category.keys() - {'Electronics'}}  # Electronics key will be
print('Categories:', new_dict)

Output –

                    

Categories: {'Clothing': 'Tshirt', 'Toys': 'Remote Car', 'Grocery': 'Vegetables'}

Advantages of using Dictionary Comprehension

One of the major advantages of using dictionary comprehension is that it shortens the number of lines of codes. This also provides a more Pythonic code. The logic remains the same, but the readability of the code becomes easier.

Another advantage being substituting dictionary comprehension in place of for loops or lambda functions. Not all for loops can be written in dictionary comprehension, but most of them can be converted and this can provide a much easier solution for the programmer to understand the problem and code with ease.

Warnings on using Dictionary Comprehension

Dictionary comprehensions are fantastic for writing easy-to-read code, but they aren’t always the best option. Sometimes they are troublesome for decoding any error.

  • They can slow down the code and at times consume more memory space.
  • Writing nested dictionary comprehensions can be difficult to read and should be avoided.
  • Fitting difficult logical codes into dictionary comprehension can create lots of problems.
  • This results in a decrease in the readability of the code.

Frequently Asked Questions

Q1. What is dictionary comprehension in Python?

Python dictionary comprehension method is used to create efficient dictionaries in a single line of code. In Python, Dictionary comprehension allows you to generate dictionaries in a Pythonic, clean, and easy-to-understand manner.

Many times, we use excess conditional statements or looping statements in order to execute one single logical problem in our code. But this can be avoided by using the Python dictionary comprehension method. This is useful because it saves coding lines, and makes the code more readable.

Q2. How do you use dictionary comprehension in Python?

Dictionary comprehension must be always written in a specific format. The syntax is mentioned below.

Syntax –

                    

dictionary = {key: value for vars in iterable}

where,

vars = can either be variables declared or (key, value) pair

iterable  = any object which we can loop over. E.g. list, tuple, string.

Example –

                    

subjects = ['History', 'Science', 'English', 'Maths', 'Geography', 'EVS']

# dictionary comprehension
new_dict = {k:len(k) for k in subjects}
print(new_dict)

Output –

                    

{'History': 7, 'Science': 7, 'English': 7, 'Maths': 5, 'Geography': 9, 'EVS': 3}

Q3. What are dict and list comprehensions in Python?

List and dictionary comprehensions give you a quicker way to make lists and dictionaries by providing more functionalities.

List comprehensions are a more compact and elegant alternative to for-loops for creating lists, and they also allow you to generate lists from existing lists. A list comprehension is made up of brackets[] that contain an expression, a for clause, and zero or more for or if clauses.

Syntax –

                    

list = [expression for item in iterable]

Dictionary comprehensions are similar to list comprehensions in Python, but they only work with dictionaries. They offer a simple way to make a dictionary from an iterable or to convert one dictionary to another. Curly braces {} are used to write dictionary comprehension. The separator between the key and the value in Expression is ‘:’

Syntax –

                    

dictionary = {key: value for vars in iterable}

Q4. How do you create a dictionary by using 2 lists?

If we have declared 2 lists, we can merge them into a dictionary using the Python dictionary comprehension method. We also take the help of the zip function. Let us understand this by looking at the below example.

Example –

                    

# Python program to create a dictionary from lists
roll_no = [1, 2, 3, 4, 5]
students = ['Sam', 'Emily', 'John', 'Kris', 'Zack']

new_dict = {key: value for (key, value) in zip(roll_no, students)}
print('New Dictionary: ', new_dict)

Output –

                    

New Dictionary: {1: 'Sam', 2: 'Emily', 3: 'John', 4: 'Kris', 5: 'Zack'}

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.