Python KeyError Examples
Short, runnable programs that show python keyerror: what it means and how to fix it in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python KeyError: What It Means and How to Fix It lesson.
1Reading nested JSON safely with get()
Chaining get() with an empty dictionary as the default lets you dig into nested data without a KeyError at any level.
profiles = [
{"name": "Asha", "address": {"city": "Pune", "zip": "411001"}},
{"name": "Ben", "address": {}},
{"name": "Chen"},
]
for p in profiles:
city = p.get("address", {}).get("city", "unknown")
print(p["name"], "lives in", city)Expected outputAsha lives in Pune
Ben lives in unknown
Chen lives in unknown
2Counting with defaultdict(int)
A defaultdict(int) treats every missing key as 0, so += 1 works the very first time a key appears. Be aware that even reading a missing key adds it, as 'zebra' shows.
from collections import defaultdict
sentence = "the quick fox and the lazy dog and the cat"
counts = defaultdict(int)
for word in sentence.split():
counts[word] += 1
print(counts["the"], counts["and"], counts["fox"])
print("zebra:", counts["zebra"])
print(dict(counts))Expected output3 2 1
zebra: 0
{'the': 3, 'quick': 1, 'fox': 1, 'and': 2, 'lazy': 1, 'dog': 1, 'cat': 1, 'zebra': 0}
3Grouping with setdefault()
setdefault(key, []) creates an empty list for a new key and returns the list that is stored there, so you can append() in one line.
students = [("Asha", "7A"), ("Ben", "7B"), ("Chen", "7A"), ("Dara", "7C")]
classes = {}
for name, group in students:
classes.setdefault(group, []).append(name)
for group, names in classes.items():
print(group, "->", names)Expected output7A -> ['Asha', 'Chen']
7B -> ['Ben']
7C -> ['Dara']
4Deleting keys without a KeyError
del d[key] and d.pop(key) both raise KeyError for a missing key. d.pop(key, None) returns None instead.
cart = {"tea": 2, "cake": 1}
del cart["tea"]
try:
del cart["tea"]
except KeyError as err:
print("Already removed:", err)
print(cart.pop("tea", None))
print(cart.pop("cake", None))
print(cart)Expected outputAlready removed: 'tea'
None
1
{}
Practise next
Python KeyError: What It Means and How to Fix It exercises → Back to the lesson
Python Dictionaries examplesPython Exceptions: try, except, else and finally examplesPython IndexError: list index out of range examplesWorking with JSON in Python examples