dict.get() / dict.setdefault()
Methods for safely retrieving keys from a dictionary and setting default values when a key does not exist. They are essential for preventing KeyError.
Syntax
# Returns the value for the key. Returns the default value if the key does not exist. dict.get(key, default=None) # If the key does not exist, sets the default value and returns it. If the key already exists, returns the existing value. dict.setdefault(key, default=None)
Method List
| Method | Description |
|---|---|
| dict.get(key, default=None) | Returns the value for the key if it exists, otherwise returns default. The dictionary is not modified. |
| dict.setdefault(key, default=None) | Returns the value for the key if it exists. If the key does not exist, adds key: default to the dictionary and returns default. |
Sample Code
# Use get() to retrieve a value without raising an error if the key is missing.
person = {"name": "Taro", "age": 20, "city": "Tokyo"}
# Retrieve an existing key.
print(person.get("name")) # Taro
print(person.get("age")) # 20
# Retrieving a missing key with get() returns None.
print(person.get("email")) # None
# Specify a default value.
print(person.get("email", "Not registered")) # Not registered
print(person.get("phone", "000-0000")) # 000-0000
# The difference between get() and [].
# person["email"] # Raises KeyError.
# person.get("email") # No error — returns None.
# A practical example: branch logic based on a config value.
config = {"debug": True, "timeout": 30}
log_level = config.get("log_level", "INFO") # Default is "INFO"
print(f"Log level: {log_level}") # Log level: INFO
# Use setdefault() to set a value only when the key is absent.
user = {"name": "Hanako"}
user.setdefault("role", "guest") # "role" is missing, so it is added.
print(user) # {'name': 'Hanako', 'role': 'guest'}
user.setdefault("role", "admin") # "role" already exists, so nothing changes.
print(user) # {'name': 'Hanako', 'role': 'guest'} (not changed to admin)
# A common pattern: using setdefault() to group items into lists.
# Convenient for building a "dict of lists" structure.
fruits_by_color = {}
items = [
("red", "apple"), ("yellow", "banana"), ("red", "strawberry"),
("green", "grape"), ("yellow", "lemon")
]
for color, fruit in items:
fruits_by_color.setdefault(color, []).append(fruit)
print(fruits_by_color)
# {'red': ['apple', 'strawberry'], 'yellow': ['banana', 'lemon'], 'green': ['grape']}
# The same result can be achieved with collections.defaultdict.
from collections import defaultdict
fruits_by_color2 = defaultdict(list)
for color, fruit in items:
fruits_by_color2[color].append(fruit)
print(dict(fruits_by_color2)) # Same result.
# Count word occurrences using get().
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
print(count) # {'apple': 3, 'banana': 2, 'cherry': 1}
Notes
When accessing a dictionary value, using [] with a key that does not exist raises a KeyError. Whenever you are unsure whether a key exists, always use get() or check with the in operator before accessing it.
The key difference between setdefault() and get() is whether the dictionary is modified. setdefault() adds a default value to the dictionary when the key is absent. This behavior is commonly used in the pattern of setting an empty list on the first access and appending data to it thereafter.
For counting or aggregating words, collections.Counter from the standard library is more concise. For updating and removing dictionary entries, see dict.update() / dict.pop().
If you find any errors or copyright issues, please contact us.