Dictionaries

A dictionary maps keys to values.

Output:

2

Use a dictionary when you want to look up a value by name, label, id, or other key.

Keys and Values

In this dictionary:

counts = {"cat": 2, "dog": 1}

"cat" and "dog" are keys. 2 and 1 are values.

The key answers "which one?" The value answers "what is stored there?"

Updating a Dictionary

You can assign a key:

counts["bird"] = 3

You can update an existing key:

counts["cat"] = counts["cat"] + 1

This pattern is useful for counting.

Count words

The dictionary stores a count for each word.

Runs locally with Python in your browser.

Ready to run.

Iterating Over Items

Use .items() when you need both key and value:

The order is not the main point of a dictionary. The mapping is.

Keys Must Be Looked Up Exactly

Looking up a missing key causes a KeyError:

Check first, or use patterns that handle missing keys.

One compact counting pattern uses .get():

counts[word] = counts.get(word, 0) + 1

counts.get(word, 0) returns the stored count when the key exists and the default value 0 when it does not. This avoids a missing-key error while keeping the initial count visible.

Exercise: Read a dictionary value

What does this print?

Compute it first, then check your number.

HintFollow the key

Find the key "blue", then read the value written after its colon.

SolutionBlue maps to five

The dictionary pair is "blue": 5, so counts["blue"] produces 5 and the print call displays it.

Dictionaries Connect Keys to Values

Dictionaries are the first container that gives values names inside the data itself. They are central to small data programs.