Skip to content
dreamcode
dreamcode
Map
Dict comprehensions
Lesson 32 of 77
+15 XP on finish
PYTHON INTERMEDIATEChapter 6 · Comprehensions and data tools

Dictionary comprehensions

A dictionary comprehension builds dictionaries using key-value expressions: {key_expr: value_expr for item in iterable}.

Worked example

How it reads

  • {n: len(n) ...} maps name to its length as key and value
  • for n in names defines the source iterable loop
Cloud tip: Like list comprehensions, you can add conditional if checks at the end of a dict comprehension.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Build a dict that maps each name to its length and print it: {'Alice': 5, 'Bob': 3}.

Press Run to check your work.