Skip to main content

Python Tutorial 9.2 - Dictionary Comprehensions

Dictionary comprehensions let you build dictionaries in a single, readable expression.


Syntax

{key_expr: value_expr for item in iterable if condition}

Example

# Map numbers to their cubes for numbers 0–4
cubes = {x: x**3 for x in range(5)}
print(cubes)  # {0: 0, 1: 1, 2: 8, 3: 27, 4: 64}

Key Takeaways

  • Use curly braces {} with key: value pairs.
  • Filter items with an if clause as needed.
  • Great for transforming sequences into lookup tables.

Happy coding!

Comments