Python Basics for Vibe Coders, Part 6: Dictionaries, Looking Up Values by Key, and KeyError
Look up Python dictionary values by key, add or update them, and loop with items(). Handle KeyError with get() and fix AI code for JSON responses.
Ask an AI for code that works with a weather API or a config file, and you'll see plenty of lines like data["name"] and config.get("timeout"). That's a dictionary, which finds values by name (the key). JSON data sent back and forth on the web is read into Python as a dictionary, too, as long as it's an object wrapped in {}. This is Part 6 of the 10-part series "Python Basics for Vibe Coders." It covers reading, adding, and updating values in a dictionary, and how to use get to safely handle the KeyError you get from a missing key. The examples are written for Python 3.15, and I ran them in Python 3.14.2 to check the results.
Key Takeaways
- A dictionary is a set of
key: valuepairs inside curly braces{}. You look things up by name, not by number.- Assigning to an existing key doesn't create a new entry. It changes the value. Keys are never duplicated.
- Looking up a missing key with
[]raises aKeyError. Read keys that might be missing withget(key, default).items()lets you loop over keys and values together.
A dictionary is a phone book
In a phone book, you find a number (the value) directly by name (the key). Where the lists from Part 5 find things by "which position," a dictionary finds them by "which name."
People also compare it to a word dictionary, but that comparison has a limit. A word dictionary just tells you a word isn't there. A Python dictionary, when you look up a missing key with [], raises an error and stops the program. That difference is the heart of this post.
Read, add, and loop
scores = {"English": 90, "Math": 85}
scores["History"] = 70
print(scores["Math"])
print(scores.get("Science", 0))
for subject, score in scores.items():
print(subject, score)
85
0
English 90
Math 85
History 70
| Code | Meaning |
|---|---|
scores["Math"] | Read the value for the "Math" key. KeyError if the key is missing |
scores["History"] = 70 | Add the key if it's missing, update the value if it exists |
scores.get("Science", 0) | If the key is missing, return the default 0 instead of an error |
scores.items() | Get keys and values as pairs |
for subject, score in scores.items(): takes one pair at a time and assigns the key to subject and the value to score. It's the most common shape you'll see in AI code that walks through a dictionary.
Common trap: is a missing key None, or KeyError?
scores = {"English": 90}
try:
print(scores["Science"])
except KeyError as e:
print("KeyError:", e)
KeyError: 'Science'
It's an error, not None. The error message shows the exact key you were looking for ('Science'), so when you see it, read it as "that key isn't in the data." Often the cause is a typo (like a trailing space in "Math ") or a difference in capitalization ("Name" vs. "name").
For keys that might be missing, read them with get and give a default. On the other hand, if a key must always be there, it's better to read it with [] and let it fail right away when it's missing. That way you find the problem early.
Where you'll meet dictionaries in vibe coding: JSON
When you read JSON, the format used for API responses and config files, with Python's json module, a JSON object in {} becomes a dictionary and a JSON array in [] becomes a list.
import json
data = json.loads('{"name": "Mia", "age": 20}')
print(data["name"], data.get("email", "N/A"))
Mia N/A
If AI-written API code throws a KeyError, the cause is often that the keys in the data you actually received differ from the keys the AI expected. In that case, rather than just asking the AI to rewrite the code, it's faster to show it the real response first.
- Print the data you received with
print(data), or see the list of keys withprint(data.keys()). - Paste that output into the AI (after removing personal info, keys, and tokens) and ask: "Here's what the actual response looks like. Fix the code to match it."
Check yourself
- With
d = {"a": 1}, what isd["b"]? →KeyError.[]raises an error for a missing key. If you pickedNone, you mixed it up withget. - What happens if you run
d["c"] = 3on a dictionary that already has a"c"key? → The existing value changes to 3. Unlike a list'sappend, no new entry is added.
Try it yourself
Make a dictionary that maps 3 friends' names to phone numbers. Given a name, print the number, or print "Not registered" if the name isn't there. If both a known name and an unknown name work without errors, you've got it. If you get stuck, check the second argument to get.
phones = {"Mia": "555-0101", "Sam": "555-0102", "Leo": "555-0103"}
print(phones.get("Sam", "Not registered"))
print(phones.get("Emma", "Not registered"))
555-0102
Not registered
Previous and next
- Previous: Part 5: Lists and Indexes That Start at 0
- Next: Part 7: Functions covers functions, which let you name code and reuse it, and the difference between
printandreturn.
The full series list is at the end of Part 10.