PythonObjectsIntermediate

Dictionary comprehensions

Builds a dict in one expression from an iterable (optionally filtered).

Review the syntaxStudy the examplesOpen the coding app
{key_expr: value_expr for item in iterable if condition}

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Builds a dict in one expression from an iterable (optionally filtered).

Dictionary comprehensions provide a declarative and concise syntax for constructing dictionaries from iterables. Internally, they are often more performant than manual for-loops because the dictionary construction occurs as a single operation within the Python interpreter's C-level code, reducing the overhead of repeated attribute lookups like .update() or .__setitem__(). While highly readable for simple transformations, they have a memory footprint of O(N) as the entire dictionary is instantiated in memory immediately, unlike generator expressions which are lazy. A significant edge case is 'Key Collision': if the iterable yields identical keys, the comprehension silently overwrites previous entries with the most recent value, which can result in unintended data loss during operations like dictionary inversion.

Quick reference

Syntax

{key_expr: value_expr for item in iterable if condition}

Inputs

Parameters

key_exprexpression · Expression that produces a key.
value_exprexpression · Expression that produces a value.
condition (optional)expression · Optional filter expression.

See it in practice

Examples

1

Basic Value Transformation

squares = {x: x**2 for x in range(6)}
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Creates a dictionary where keys are integers and values are their respective squares.

2

Conditional Filtering

prices = {'apple': 0.5, 'banana': 0.25, 'cherry': 1.25}
expensive_items = {k: v for k, v in prices.items() if v > 0.4}
Output:
{'apple': 0.5, 'cherry': 1.25}

Filters an existing dictionary based on a value threshold using an if-clause.

3

Dictionary Inversion

colors = {'primary': 'red', 'secondary': 'orange'}
swapped = {v: k for k, v in colors.items()}
Output:
{'red': 'primary', 'orange': 'secondary'}

Swaps keys and values to create a reverse lookup table.

Debug faster

Common Errors

1

TypeError

Cause: Attempting to use a mutable object (like a list) as a dictionary key.

Fix: Use immutable types like strings, integers, or tuples for keys.

invalid = {['a']: 1 for x in range(1)}
2

LogicError

Cause: Key collisions during inversion when multiple original keys share the same value.

Fix: Ensure uniqueness of values before inverting or use a grouping logic with lists.

data = {'a': 1, 'b': 1}
inverted = {v: k for k, v in data.items()} # Result: {1: 'b'}, 'a' is lost

Runtime support

Compatibility

Python 3.8+

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Builds a dict in one expression from an iterable (optionally filtered).

xpr: Expression that produces a key. xpr: Expression that produces a value. condition: Optional filter expression.

TypeError: Use immutable types like strings, integers, or tuples for keys. LogicError: Ensure uniqueness of values before inverting or use a grouping logic with lists.