Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

3.2 Dictionaries

How it works

A dictionary maps keys to values with constant average lookup. Keys must be hashable, which excludes lists.

Reach for a dictionary whenever you would otherwise keep two parallel lists in step.

Common error

Indexing a missing key raises rather than returning nothing; use a default lookup when absence is expected.

Worked example

Python

counts = {}
for word in ["red", "blue", "red"]:
    counts[word] = counts.get(word, 0) + 1
print(counts["red"])
print(counts.get("green", 0))

Output

2
0

A dictionary associates keys with values. get can supply a fallback without inserting the missing key, while assigning a value creates or updates a mapping.

Exercises

3.2.1 · Trace

Determine the exact output and explain the state changes.

Python

data = {"a": 1, "b": 2}
data["a"] = 5
print(len(data), data["a"])
Show solution

Output

2 5

Updating an existing key changes its value without increasing the number of keys.

3.2.2 · Write code

Build a frequency dictionary for [2, 2, 3] and print the counts in sorted key order.

Show solution

Sorting the keys makes output deterministic.

One valid solution

counts = {}
for value in [2, 2, 3]:
    counts[value] = counts.get(value, 0) + 1
for key in sorted(counts):
    print(key, counts[key])

Expected output

2 2
3 1
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic