Lesson 8: Dictionaries and Data Structures
Create and use dictionaries; represent structured data in Python.
By Bishwambhar Sen • Last updated • 55 min
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).
Creating and Accessing Dictionaries
Dictionaries use curly braces {} and colons : to separate keys and values.
"accuracy": 0.92,
"precision": 0.89,
"recall": 0.94
}
To access a value, you use square brackets with the key name instead of an index number.
Dictionaries in AI Data
Dictionaries are perfect for representing structured data, like rows in a dataset or nested relationships like a confusion matrix.
Reading, Adding and Updating Entries
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)) # 2Looping Over a Dictionary
A 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.
Worked Example: Counting with .get()
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.
Nested Dictionaries and Lists of Dictionaries
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).
What Can Be a Key?
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.
Common Pitfalls
- KeyError from a typo.
metrics["Accuracy"]fails if the key is"accuracy". Keys are case sensitive. - Modifying a dictionary while looping over it. Adding or removing keys inside the loop raises a
RuntimeError. Loop overlist(d)instead if you must. - Confusing an empty dictionary with an empty set.
{}is an empty dict; useset()for an empty set. - Assuming a copy.
b = amakes both names point at the same dictionary. Usea.copy()for an independent shallow copy.
Recap
- A dictionary maps unique, immutable keys to values; look values up with
d[key]ord.get(key, default). .items()gives key-value pairs for loops.- The
counts[w] = counts.get(w, 0) + 1idiom is the basis of word counting. - Lists of dictionaries are the in-memory form of JSON and of tabular records.
Coding Challenge: Word Frequencies
A core concept in Natural Language Processing (NLP) is counting how often words appear in text. Let's do that with a dictionary!
- We have a list of words:
words = ["AI", "is", "fun", "AI", "is", "cool"]. - Create an empty dictionary called
word_counts = {}. - Write a
forloop to iterate over thewordslist. - Inside the loop: if the word is already a key in
word_counts, add 1 to its value. Otherwise, add the word as a new key with the value 1. - Print the resulting dictionary.