Dicts

If you're coming from another language

A Python dict is the equivalent of Java’s HashMap, JS’s plain object (or Map), or C#’s Dictionary — a collection of key-value pairs, looked up by key instead of position.

Try it — edit and run

Key access, and the difference between [] and .get()

Direct bracket access raises an error if the key doesn’t exist:

Try it — edit and run

.get() returns None instead of crashing, and optionally lets you specify a fallback value:

Try it — edit and run

Use .get() whenever a missing key is a normal possibility rather than a bug; use [] when a missing key should be treated as an error worth crashing on (or catch it explicitly with try/except KeyError, from Lesson 0.1).

Modifying a dict, and iterating over it

Try it — edit and run

Three ways to loop over a dict, depending on what you need:

Try it — edit and run

.items() returns each pair as a (key, value) tuple, which is why for key, value in ... works: it’s unpacking, exactly like Concept 2’s tuple unpacking, just happening automatically once per loop iteration.

The tally pattern

A very common use of dicts: counting occurrences of something, building the dict up as you go.

Try it — edit and run

.get(msg, 0) is what makes this work without pre-declaring every possible key: the first time msg appears, .get() returns 0 (the fallback) since the key isn’t there yet, and + 1 makes it 1. Every time after that, .get() returns the running count, and + 1 increments it.

Check your understanding
1/3

What's the practical difference between config["model"] and config.get("model") when "model" isn't a key in config?

Exercise · Graded

Build a dict from scratch, incrementing a count for each vote as you loop through the list. (The tally pattern, standalone.)