← Back to Chapters

Python Dictionary Comprehension

? Python Dictionary Comprehension

? Quick Overview

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 Concepts

  • Key–Value Creation: Each iteration generates one key: value pair.
  • Based on Iterable: You can loop over range(), lists, tuples, or other iterables.
  • Optional Condition: Add an if at the end to filter which items are included.
  • Transform Existing Dictionaries: Use dict.items() to update or remap keys and values.
  • Swap Keys and Values: Create a reversed mapping using {v: k for k, v in dict.items()}.

? Syntax & Theory

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.

? Code Examples

⚡ Basic Dictionary Comprehension

Create a dictionary of numbers and their squares using a single line of code:

? View Code Example
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.

? Dictionary Comprehension with Condition

Use an if condition to include only certain items in the dictionary. This is useful for filtering data while creating the dictionary.

? View Code Example
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.

? Transform Existing Dictionary

Dictionary comprehension can also be used to transform an existing dictionary. You can modify values, filter items, or even swap keys and values.

? View Code Example
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.

? Live Output & Explanation

? Sample Outputs

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.

✅ Tips & Best Practices

  • Use dictionary comprehension for concise and readable dictionary creation.
  • Combine comprehension with an if condition for efficient filtering.
  • Use items() to iterate over existing dictionaries when transforming values or keys.
  • Dictionary comprehension can also be used to swap keys and values: {v: k for k, v in some_dict.items()}.
  • If the logic gets too complex, consider using regular loops for better readability.

? Try It Yourself

  • Create a dictionary of numbers and their cubes using comprehension: {x: x**3 for x in range(1, 11)}.
  • Create a dictionary of even numbers and their squares using a condition.
  • Transform an existing dictionary of item prices by applying a 10% discount.
  • Swap keys and values of an existing dictionary using comprehension.
  • Try filtering a dictionary to keep only items above a certain price.