Python - Dictionaries

Overview

Estimated time: 25–35 minutes

Use dictionaries (hash maps) for key-value storage. Learn lookups, updates, iteration, and helpful methods.

Learning Objectives

  • Create and update dicts; understand key immutability and hashing.
  • Use get, setdefault, update, and dict comprehensions.
  • Iterate with keys(), values(), and items().

Prerequisites

Basics

user = {"name": "Ada", "age": 36}
user["role"] = "admin"
print(user.get("email", "(none)"))

Counting with dict

counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

Comprehensions and iteration

squares = {n: n*n for n in range(5)}
for k, v in squares.items():
    print(k, v)

Common Pitfalls

  • Using mutable types as keys; keys must be hashable (e.g., tuples, not lists).
  • Assuming dict reorder; since 3.7, insertion order is preserved by language guarantee.

Checks for Understanding

  1. How do you get a default value for a missing key?
  2. Which method returns key-value pairs for iteration?
Show answers
  1. dict.get(key, default)
  2. dict.items()

Exercises

  1. Build a frequency map of words from a string.
  2. Invert a dict where values are unique (value → key).