Skip to main content
Module 3 · Lesson 3 of 411/36 in the course~16 min
Module lessons (3/4)

Dictionaries

Lesson preview5 hands-on exercises readyPython Course · Module 3 — Data structures

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 dict and understand constant-time lookup O(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

  1. 1The mental model: hash table sorted by key
  2. 2Secure vs fail-fast access
  3. 3Idiomatic iteration and aggregation with setdefault
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 3 — Data structures

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.