What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Dictionary Comprehension: Syntax & Cases (with code)

  • Mar 06, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Python Dictionary Comprehension: Syntax & Cases (with code)

Dictionaries are considered an integral part of python due to their efficiency in storing data. These key-value pairs allow you to retrieve data with ease. We will explore the concept of dictionary comprehension in Python and its syntax and its practical applications.

What is Dictionary Comprehension?

Much like list comprehension, dictionary comprehension is a method to make dictionaries easy. Dictionary comprehension in Python is a concise way to create a dictionary from an iterable object. It is a one-line expression that combines the functionality of loops, conditional statements, and dictionary initialization to generate a dictionary in a single line of code.

To conceptualize dictionary comprehension we need to know how a dictionary works in python.

Let us consider a real-life dictionary, if we had to look for a definition of any word, we would do so by looking for the word and then looking for the definition. Similarly in a python dictionary, we have a key and its value I.e the key-value pair. The key is used to access or in a way trace the value associated with it.

In dictionary comprehension, this very same dictionary is expressed or more precisely written in a concise syntax.

Is dictionary comprehension faster in Python? Yes, Dictionary Comprehension is faster because it is a highly optimized way to create dictionaries by taking use of a python interpreter more effectively. Dictionary comprehension combines it all in a single expression for faster execution. It also avoids the need to initialize an empty dictionary and append elements to it one by one.

However, the performance gain may not be significant for small datasets.

How to make Dictionary Comprehension in Python?

We will now dive into understanding the python code and learn how to implement dictionary comprehension in various ways.

The general syntax used in dictionary comprehension is:

dict_comprehension = {key: value for x in iterable}

Let us look at a simple example to grasp the difference between a dictionary and dictionary comprehension:

Consider a dictionary called Houses, the key expression is the house names (1-5) and the value expression is the house number. The house number is denoted by house name + area code (1110) this is how we would write the code :

Houses = {1: 1111, 2: 1112, 3: 1113, 4: 1114, 5: 1115}
print( houses) 



{1: 1111, 2: 1112, 3: 1113, 4: 1114, 5: 1115}


Or we could use dictionary comprehension to simplify the code:

houses = {num: num+1110 for num in range(1,6)}



{1: 1111, 2: 1112, 3: 1113, 4: 1114, 5: 1115}


List comprehension lightens the code and is much easier to write and execute when there are larger data, for understanding consider there are 1000 such houses. Writing the dictionary without it would make it a tedious process.

There are various ways where we can use dictionary comprehension, we can use it concisely from 2 lists, if-else blocks, changing old dictionaries, and more. Let us look at some cases below:

Case 1: Conditional or If-else

Let us consider a list of marks for class 8 students called marks_8A. Now we want to determine who has failed and who has passed. Here we will use conditional statements to assign values to the respective keys. The condition is If the person has scored 38 and above they have passed, or else they failed.

marks_8A = (12,40,89,79,38,72,94,95,37)
results = { marks: "pass" if marks >= 38 else "fail" for marks in marks_8A}



 {12: 'fail', 40: 'pass', 89: 'pass', 79: 'pass', 38: 'pass', 72: 'pass', 94: 'pass', 95: 'pass', 37: ‘fail'}


Case 2: Combining 2 lists

If we want to combine 2 lists that are associated, we can do using dictionary comprehension. Lets us consider a list called names and another called Fav_food with their respective preferences

name = ("ayesha","bernadette","imraan","amari")
Fav_food = ("vada pav", "nutella", "baklava", "hummus")
preferences = {name:food for name,food in zip(name,Fav_food)}
print( preferences)



{'ayesha': 'vada pav', 'Bernadette': 'Nutella', 'Emraan': 'baklava', 'amari': ‘hummus’}


Note: Using the built-in Python function zip(), you can merge different iterables into a single tuple iterator.

Yes, you may combine different lists into a list of tuples using the zip() function.

Case 3: Updating a dictionary

Let us consider a saloon’s old price chart in a dictionary called - old_prices. Due to inflation, the prices need to increase by 20%. We will update this dictionary using list comprehension

#item price in dollars
old_price = {'hair cut': 50, 'manicure':30, 'pedicure': 25, 'shaving': 25, 'hair spa': 45,}
inflation = 0.20
new_price = {service: price + price*inflation for (service, price) in old_price.items()}



{'hair cut': 60.0, 'manicure': 36.0, 'pedicure': 30.0, 'shaving': 30.0, 'hair spa': 54.0}


Case 4: Setting default values

Let us consider a game of bowling, we have a dictionary of previous players called - points, and we want to reset the values. Here’s how we code it.

points = {'player 1':23, 'player 2':10, 'player 3':30, 'player 4':12}
new_round = {point: None for point in points}



{'player 1': None, 'player 2': None, 'player 3': None, 'player 4': None}



We discussed everything a beginner should learn about Dictionary Comprehension in Python. Simply put, it is a really cool feature of Python that makes creating dictionaries really quick and effective. It is adaptable, capable of filtering and mapping, and secures the keys to prevent mistakes with them. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.