0Pricing
Python Academy · Lesson

Dictionary Comprehensions

Build dictionaries concisely with comprehension syntax.

Dictionary Comprehensions is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Dictionary comprehensions provide a concise way to build dicts from any iterable.

Basic Dict Comprehension

{k: v for k, v in items} is the base form. Example: {x: x**2 for x in range(5)} maps numbers to their squares.
squares = {x: x**2 for x in range(5)}
print(squares)

With a Condition

Add if at the end to filter: {x: x**2 for x in range(10) if x % 2 == 0} keeps only even numbers.
evens = {x: x**2 for x in range(10) if x % 2 == 0}
print(evens)

Inverting a Dict

{v: k for k, v in d.items()} swaps keys and values. Only works if all values are unique and hashable.
d = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in d.items()}
print(inverted)

From Two Lists

{k: v for k, v in zip(keys, values)} is the cleanest way to build a dict from parallel lists.
keys = ['name', 'age']
vals = ['Alice', 30]
d = {k: v for k, v in zip(keys, vals)}
print(d)

Transforming Values

Apply a function to all values: {k: v.upper() for k, v in d.items()} converts all string values to uppercase.
d = {'a': 'hello', 'b': 'world'}
result = {k: v.upper() for k, v in d.items()}
print(result)

Nested Dict Comprehension

{outer_k: {inner_k: inner_v} ...} nests comprehensions. Keep readability in mind — if it's complex, use a regular loop.
nested = {i: {j: i*j for j in range(3)} for i in range(3)}
print(nested)

Grouping with Comprehension

Group items by a property: {k: [v for v in values if condition(v, k)] for k in keys}
words = ['apple', 'art', 'banana', 'blueberry']
grouped = {ch: [w for w in words if w.startswith(ch)] for ch in 'ab'}
print(grouped)

Merging and Overriding

{**d1, **d2} merges two dicts in a comprehension-like way. d2 values win on duplicate keys.
d1 = {'a': 1, 'b': 2}
d2 = {'b': 99, 'c': 3}
merged = {**d1, **d2}
print(merged)

Dict vs defaultdict

Comprehensions create plain dicts. Use defaultdict when you need auto-initialization for missing keys.
from collections import defaultdict
d = defaultdict(list)
for w in ['apple', 'art', 'banana']:
    d[w[0]].append(w)
print(dict(d))

Performance

Dict comprehensions are generally faster than equivalent for-loop builds because the interpreter optimizes them internally.
# Comprehension
squares = {x: x**2 for x in range(1000)}
print(len(squares))

Quick Check

What does {v: k for k, v in d.items()} do?

Recap

Dict comprehensions: {k: v for ... if ...}. Use for inverting, transforming values, grouping, and filtering. Combine with zip() for parallel lists.

Keep Going

Great work! Move on to the next lesson to continue building your skills.

Frequently asked questions

Is the “Dictionary Comprehensions” lesson free?

Yes — the full text of “Dictionary Comprehensions” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Dictionary Comprehensions”?

Build dictionaries concisely with comprehension syntax. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Dictionary Comprehensions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Dictionary Basics
  2. Dictionary Methods
  3. Sets and Set Operations
  4. Dictionary Comprehensions
← Back to Python Academy