Sometimes a simple list isn't enough. When data has labeled properties, we need Dictionaries.
A Dictionary in Python is a collection of key-value pairs. Think of it like a real dictionary: you look up a word (the key) to find its definition (the value).
Dictionaries use curly braces {} and colons : to separate keys and values.
To access a value, you use square brackets with the key name instead of an index number.
Dictionaries are perfect for representing structured data, like rows in a dataset or nested relationships like a confusion matrix.
Dictionaries are mutable, so you can change them after creation. Assigning to a key that exists updates its value; assigning to a new key adds an entry. Reading a key that does not exist raises a KeyError, which is why the .get() method is so useful: it returns a default instead of crashing.
metrics = {"accuracy": 0.92, "precision": 0.89}
metrics["recall"] = 0.94 # add a new key
metrics["accuracy"] = 0.93 # update an existing key
print(metrics.get("f1", "not computed")) # not computed
print("recall" in metrics) # True (checks keys, not values)
del metrics["precision"] # remove an entry
print(len(metrics)) # 2A plain for loop over a dictionary walks its keys. To get both keys and values at once, use .items(), which yields (key, value) pairs. Since Python 3.7, dictionaries remember insertion order, so the loop visits entries in the order you added them.
scores = {"cat": 0.81, "dog": 0.12, "bird": 0.07}
for label, probability in scores.items():
print(f"{label:>5}: {probability:.0%}")
best = max(scores, key=scores.get) # key with the largest value
print("Prediction:", best) # Prediction: catThis is exactly the shape of a classifier's output: one probability per class. Picking the key with the highest value is how a model turns those probabilities into a single predicted label.
The word-frequency challenge below asks you to add 1 to a count if the word is present and start at 1 otherwise. There is a compact idiom for this that avoids the explicit if:
words = ["AI", "is", "fun", "AI", "is", "cool"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'AI': 2, 'is': 2, 'fun': 1, 'cool': 1}Read the middle line from the inside out: counts.get(word, 0) returns the current count, or 0 when the word is new; adding 1 and storing it back updates the entry. The standard library also provides collections.Counter that does this in one call, but writing the loop once teaches you what it does.
Values can be anything, including lists and other dictionaries. A very common structure in AI work is a list of dictionaries, where each dictionary is one record. This is almost exactly what JSON looks like, and it is the format most web APIs, including AI model APIs, use to exchange data.
houses = [
{"bedrooms": 3, "sqft": 1500, "price": 250000},
{"bedrooms": 4, "sqft": 2100, "price": 340000},
]
total = 0
for house in houses:
total += house["price"]
print(total / len(houses)) # 295000.0In a later lesson, pandas will turn this exact structure into a DataFrame with one line: pd.DataFrame(houses).
Keys must be hashable, which in practice means immutable: strings, numbers and tuples work, lists do not. Keys must also be unique. If you write the same key twice in a dictionary literal, the later value silently replaces the earlier one.
metrics["Accuracy"] fails if the key is "accuracy". Keys are case sensitive.RuntimeError. Loop over list(d) instead if you must.{} is an empty dict; use set() for an empty set.b = a makes both names point at the same dictionary. Use a.copy() for an independent shallow copy.d[key] or d.get(key, default)..items() gives key-value pairs for loops.counts[w] = counts.get(w, 0) + 1 idiom is the basis of word counting.A core concept in Natural Language Processing (NLP) is counting how often words appear in text. Let's do that with a dictionary!
words = ["AI", "is", "fun", "AI", "is", "cool"].word_counts = {}.for loop to iterate over the words list.word_counts, add 1 to its value. Otherwise, add the word as a new key with the value 1.