Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. Dictionary comprehension

Python · Collections & Basics

Dictionary comprehension

Easypython-06
dictcomprehensioncollections

Question

What is a dictionary comprehension?

Solution

A dictionary comprehension builds a dict from an iterable in one expression, using key: value pairs.

Form

{key_expr: value_expr for item in iterable if condition}

Useful for remapping, indexing, and quick transforms without a verbose loop.

# Square each number, keyed by the number
squares = {n: n * n for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Invert a mapping (values must be unique/hashable)
roles = {"asha": "de", "ravi": "analyst"}
by_role = {role: name for name, role in roles.items()}
# {'de': 'asha', 'analyst': 'ravi'}

# Filter while building
long_words = {w: len(w) for w in ["sql", "python", "etl"] if len(w) > 3}
# {'python': 6}

# From parallel sequences
keys = ["a", "b"]
vals = [1, 2]
d = {k: v for k, v in zip(keys, vals)}

If a later key repeats an earlier one, the later pair wins. For large or complex logic, a regular loop is clearer.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext