Module lessons (3/4)
Dictionaries
Key→value maps, indexing with [] and .get(), iterating keys/values/items, and dict.setdefault().
What you'll learn in this lesson
- Model key -> value maps with
dictand understand constant-time lookupO(1). - Choose wisely between direct access
d[key](strict) and.get(key, default)(secure). - Iterate neatly over
.keys(),.values(),.items()and aggregate data with.setdefault()or|(merge).
Overview
A dictionary (dict) associates unique hashable keys with arbitrary values, offering searches, insertions and updates in constant time O(1). Since Python 3.7+ the dictionaries also guarantee the insertion order of the keys.
Think of it as an instant index: instead of going through a whole list to find "email", Python calculates the hash of the key and jumps directly to the right slot. Precisely because it is hash-based, the keys must be immutable (str, int, tuple of immutable types — never list or dict), while the values can be any object!
Sections covered in this lesson
- 1The mental model: hash table sorted by key
- 2Secure vs fail-fast access
- 3Idiomatic iteration and aggregation with
setdefault - 4Quick check
- 5Test yourself
Unlock "Dictionaries" and the full Python Course curriculum
Key→value maps, indexing with [] and .get(), iterating keys/values/items, and dict.setdefault().
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.