dict.get()
dict.get(key[, default]) any · Updated March 13, 2026 · Dict Methods The .get() method returns the value for the specified key in a dictionary. If the key is not found, it returns the default value instead of raising a KeyError. This makes it the safest way to retrieve values from a dictionary when you’re unsure whether a key exists.
Syntax
dict.get(key[, default])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
key | any | Required | The key to look up in the dictionary |
default | any | None | The value to return if the key is not found. If omitted, defaults to None |
Return Value
Returns the value associated with key if it exists, otherwise returns default. If default is not provided, returns None.
Examples
Basic usage - retrieving a value
Get a value from a dictionary:
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person.get("name"))
# 'Alice'
print(person.get("age"))
# 30
Using with a missing key
When the key doesn’t exist, .get() returns the default:
scores = {"alice": 95, "bob": 87}
print(scores.get("charlie"))
# None
print(scores.get("charlie", 0))
# 0
Practical pattern - counting with get
A very common use case is incrementing counts:
word_counts = {}
text = "the quick brown fox jumps over the lazy dog the fox"
for word in text.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
# {'the': 2, 'quick': 1, 'brown': 1, 'fox': 2, 'jumps': 1,
# 'over': 1, 'lazy': 1, 'dog': 1}
Comparing get() to bracket notation
The key difference between .get() and bracket notation:
config = {"host": "localhost", "port": 8080}
# Using get() - safe, returns default
print(config.get("timeout", 30))
# 30
# Using bracket notation - raises KeyError
print(config["timeout"])
# KeyError: 'timeout'
Nested dictionary access
Accessing nested structures safely:
users = {
"alice": {"email": "alice@example.com", "active": True},
"bob": {"email": "bob@example.com"}
}
# Safely access nested values
print(users.get("alice", {}).get("active", False))
# True
print(users.get("charlie", {}).get("active", False))
# False # Returns default since charlie doesn't exist
Using get() with different default types
The default can be any type:
data = {"items": [1, 2, 3]}
print(data.get("count", 0))
# 0
print(data.get("items", []))
# [1, 2, 3]
print(data.get("metadata", {}))
# {}
Common Patterns
Safe configuration retrieval
def get_config(key, default=None):
config = {"debug": True, "max_retries": 3}
return config.get(key, default)
# Without default - returns None
print(get_config("missing"))
# None
# With custom default
print(get_config("timeout", 60))
# 60
Merging dictionaries with precedence
defaults = {"theme": "dark", "language": "en", "notifications": True}
user_prefs = {"theme": "light"}
# Apply defaults, then override with user preferences
result = {**defaults, **user_prefs}
# Or merge iteratively
merged = defaults.copy()
for key, value in user_prefs.items():
merged[key] = value
Grouping data
from collections import defaultdict
# Using defaultdict (alternative approach)
groups = defaultdict(list)
for item in ["apple", "banana", "apricot", "blueberry", "blackberry"]:
groups[item[0]].append(item)
print(dict(groups))
# {'a': ['apple', 'apricot'], 'b': ['banana', 'blueberry', 'blackberry']}
When to Use .get() vs Bracket Notation
Use .get() when:
- You don’t know if the key exists
- You want a sensible default fallback
- You’re building counts, caches, or aggregations
Use bracket notation dict[key] when:
- You’re certain the key exists
- Missing keys should be an error (fail fast)
See Also
-
dict() — the dict constructor for creating new dictionaries
-
collections module — contains defaultdict which provides a similar pattern with .get()