dict.get() &
Missing Keys
Learn to safely access dictionary values in Python using dict.get() and handle missing keys without crashing your program.
What is a Dictionary?
A Python dictionary 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).
student = { "name": "Alice", "age": 16, "grade": "11th" }
Accessing Values with Bracket Notation
The most common way to get a value is with square brackets. You pass the key, and Python returns the associated value.
student = {"name": "Alice", "age": 16} print(student["name"]) # "Alice" print(student["age"]) # 16
The KeyError Problem
When you use bracket notation to access a key that doesn't exist, Python raises a KeyError and your program crashes.
student = {"name": "Alice", "age": 16} print(student["gpa"]) # KeyError: 'gpa' ^^^ Program crashes here!
Introducing dict.get()
The .get() method is the safe alternative. Instead of crashing, it returns a default value when the key is missing.
dict.get(key, default) # ^ ^ # key to look up value if key is missing # (defaults to None)
None if omitted).How .get() Decides What to Return
Brackets vs .get()
d = {"a": 1} d["a"] # 1 d["b"] # KeyError!
d = {"a": 1} d.get("a") # 1 d.get("b") # None
The Default Parameter
The second argument to .get() lets you control exactly what comes back when a key is missing. If you omit it, you get None.
scores = {"math": 95, "english": 88} # No default specified: returns None scores.get("science") # None # Custom default: returns 0 scores.get("science", 0) # 0 # Custom default: returns a string scores.get("science", "N/A") # "N/A"
How to Use .get() Step by Step
Example 1: Basic Usage
user = { "username": "py_coder", "email": "coder@mail.com" } # Safe access: key exists name = user.get("username", "guest") print(name) # "py_coder" # Safe access: key missing phone = user.get("phone", "Not provided") print(phone) # "Not provided"
Example 2: Counting with .get()
A classic pattern: counting occurrences of items. The .get() method makes this clean and safe.
words = ["apple", "banana", "apple", "cherry", "banana", "apple"] counts = {} for word in words: counts[word] = counts.get(word, 0) + 1 print(counts) # {"apple": 3, "banana": 2, "cherry": 1}
Example 3: Nested Dictionaries
When working with nested dictionaries (like JSON from an API), chain .get() calls for extra safety.
response = { "user": { "name": "Alice", "address": {"city": "Portland"} } } # Safe nested access user = response.get("user", {}) city = user.get("address", {}).get("city", "Unknown") print(city) # "Portland" # If "address" were missing: # {}. get("city", "Unknown") → "Unknown"
Other Ways to Handle Missing Keys
if "key" in d:except KeyError:d.setdefault(k, v).get() Does NOT Modify the Dict
A common misconception: .get() only reads. It never adds the default to the dictionary. Compare with .setdefault():
d = {"a": 1} d.get("b", 99) # 99 print(d) # {"a": 1} # "b" is NOT added
d = {"a": 1} d.setdefault("b", 99) # 99 print(d) # {"a": 1, "b": 99} # "b" IS added!
Common Mistakes
.get("key") without a second argument returns None, which can cause bugs later when you try to use the value..get("x", 5) inserts "x" into the dictionary. It does not. Use .setdefault() for that..get("age", "N/A") then doing math on the result. If "age" is missing, you get a string where you expected an integer.Comparison Summary
| Feature | dict[key] | .get(key, def) | .setdefault() |
|---|---|---|---|
| Key exists | Returns value | Returns value | Returns value |
| Key missing | KeyError | Returns default | Inserts + returns |
| Modifies dict? | No | No | Yes |
| Best for | Known keys | Read-only lookups | Building dicts |
Question 1 of 5
What does the following code print?d = {"x": 10}print(d.get("y", 5))
.get() returns the default value 5. No error is raised.Question 2 of 5
What happens when you call .get("key") without specifying a default value and the key is missing?
.get() defaults to None. It never raises a KeyError: that's the whole point of using it.Question 3 of 5
After running this code, what does d contain?d = {"a": 1}d.get("b", 2)
.get() is read-only: it does not modify the dictionary. The key "b" is never added. If you wanted to insert it, you would use .setdefault("b", 2) instead.Question 4 of 5
Which code correctly counts how many times each letter appears in "hello"?
.get(ch, 0) to safely get the current count (defaulting to 0 for new letters), adds 1, and assigns the result back. Option A would crash on the first occurrence of each letter.Question 5 of 5
What does this code print?d = {"x": None}result = d.get("x", 42)print(result)
.get() returns the actual value (None), not the default. The default is only used when the key is completely absent.