Dictionary comprehension in Python is a concise, one-line way to create or transform dictionaries. It is similar to list comprehension, but instead of producing a list, it produces a dictionary with key–value pairs.
General syntax: {key_expression: value_expression for item in iterable}
key: value pair.range(), lists, tuples, or other iterables.if at the end to filter which items are included.dict.items() to update or remap keys and values.{v: k for k, v in dict.items()}.A basic dictionary comprehension uses a loop variable to generate keys and values:
{key_expr: value_expr for variable in iterable}
You can also add a condition to include only selected items:
{key_expr: value_expr for variable in iterable if condition}
When transforming an existing dictionary, you typically iterate using for key, value in dict_obj.items(), then build a new dictionary with modified values or swapped key–value positions.
Create a dictionary of numbers and their squares using a single line of code:
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Here, x is used as the key and x**2 as the value. The dictionary is created for all numbers in the range 0 to 4.
Use an if condition to include only certain items in the dictionary. This is useful for filtering data while creating the dictionary.
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
In this example, only even numbers are included as keys, and their squares as values. The condition if x % 2 == 0 filters out odd numbers.
Dictionary comprehension can also be used to transform an existing dictionary. You can modify values, filter items, or even swap keys and values.
prices = {"apple": 2, "banana": 1, "cherry": 3}
discounted = {item: price*0.9 for item, price in prices.items()}
print(discounted) # {'apple': 1.8, 'banana': 0.9, 'cherry': 2.7}
Here, we created a new dictionary discounted by multiplying each price by 0.9. The items() method provides both key and value for transformation.
Basic squares:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Even squares:
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Discounted prices:
{'apple': 1.8, 'banana': 0.9, 'cherry': 2.7}
In each case, the comprehension builds a complete dictionary in one readable line: the loop decides how many entries you create, the key expression decides the keys, and the value expression decides the values.
if condition for efficient filtering.items() to iterate over existing dictionaries when transforming values or keys.{v: k for k, v in some_dict.items()}.{x: x**3 for x in range(1, 11)}.