01 / 20
K K V V

dict.get() &
Missing Keys

Learn to safely access dictionary values in Python using dict.get() and handle missing keys without crashing your program.

Python

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).

Python
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.

Python
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.

Python
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.

Syntax
dict.get(key, default)
#        ^          ^
#   key to look up    value if key is missing
#                     (defaults to None)
Key found
Returns the value associated with that key, just like brackets.
Key missing
Returns the default value you specified (or None if omitted).

How .get() Decides What to Return

dict.get(key, default) key in dict? (lookup) Yes value No default No KeyError raised Program continues safely

Brackets vs .get()

dict[key] (Risky)
d = {"a": 1}

d["a"]  # 1
d["b"]  # KeyError!
vs
dict.get(key) (Safe)
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.

Python
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

1
Identify the dictionary you want to read from.
2
Determine the key you need. Ask yourself: could this key ever be missing?
3
Choose a sensible default. What value should your program use if the key isn't there?
4
Call .get(key, default) and use the returned value in your logic.

Example 1: Basic Usage

Python
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.

Python
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.

Python
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

in operator
Check before accessing:
if "key" in d:
try / except
Catch the error:
except KeyError:
.setdefault()
Get and insert if missing:
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():

.get() (Read only)
d = {"a": 1}
d.get("b", 99)  # 99
print(d)
# {"a": 1}
# "b" is NOT added
vs
.setdefault() (Read + Write)
d = {"a": 1}
d.setdefault("b", 99) # 99
print(d)
# {"a": 1, "b": 99}
# "b" IS added!

Common Mistakes

✕ Forgetting the default
Writing .get("key") without a second argument returns None, which can cause bugs later when you try to use the value.
✕ Thinking .get() adds keys
Assuming .get("x", 5) inserts "x" into the dictionary. It does not. Use .setdefault() for that.
✕ Wrong default type
Using .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))

Question 2 of 5

What happens when you call .get("key") without specifying a default value and the key is missing?

Question 3 of 5

After running this code, what does d contain?

d = {"a": 1}
d.get("b", 2)

Question 4 of 5

Which code correctly counts how many times each letter appears in "hello"?

Question 5 of 5

What does this code print?

d = {"x": None}
result = d.get("x", 42)
print(result)