AtomLearnAtomLearn
DashboardGoalsPathAchievementsReviewSign In
DashboardPython CoreDicts — Advanced Patterns
Python CoreNot Started

Dicts — Advanced Patterns

.get() vs [], .setdefault(), safe iteration, comprehensions, and merging dicts

0%
Knowledge0%
Learn & Drill
Fluency0%
Drill & Speed
Retention0%
Mastery & Review
Confidence0%
All modes
Practice

Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.

Upgrade
Knowledge
Fluency
Retention

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

`[]` vs `.get()`:

python d = {'a': 1} d['b'] # KeyError — crashes d.get('b') # None — safe d.get('b', 0) # 0 — safe with default

`.setdefault()` — set a key only if it doesn't exist: ``python d = {} d.setdefault('count', 0) # sets count=0 if not present d['count'] += 1 # now safe to increment

Modifying while iterating — same trap as lists:

python d = {'a': 1, 'b': 2, 'c': 3} # This crashes in Python 3: RuntimeError: dictionary changed size for k in d: if d[k] == 2: del d[k] # Fix: iterate over a copy of keys for k in list(d.keys()): if d[k] == 2: del d[k]

Dict comprehension:

python squares = {x: x**2 for x in range(5)} # Filtering: {k: v for k, v in d.items() if v > 0}

Merging dicts (Python 3.9+):

python a = {'x': 1}; b = {'y': 2} merged = a | b # {'x':1, 'y':2} — new dict a |= b # update a in-place # Pre-3.9: {**a, **b}

Examples

Counting with setdefault vs get

All three produce the same result — Counter is most idiomatic

words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']

# Using get
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1

# Using setdefault
counts2 = {}
for w in words:
    counts2.setdefault(w, 0)
    counts2[w] += 1

# Best: use collections.Counter
from collections import Counter
print(Counter(words))  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})

How well did you understand this?

Next in Python Core

Functions — *args, **kwargs & Keyword-Only Args

Continue