Python Dict Get Value by Key Default
Last Updated :
04 Feb, 2025
We are given a dictionary in Python where we store key-value pairs and our task is to retrieve the value associated with a particular key. Sometimes the key may not be present in the dictionary and in such cases we want to return a default value instead of getting an error.
For example, if we have a dictionary like this: person = {'name': 'Alice', 'age': 25} and we attempt to access a key that doesn't exist like 'city', we can provide a default value like 'Unknown' and in this way we avoid errors and ensure the program continues running smoothly.
Using get() with Default Value
get() method is a built-in method for dictionaries that allows you to retrieve the value for a specified key. It takes two arguments - the key you want to retrieve and a default value to return if the key is not found.
Python
car = {'brand': 'Toyota', 'year': 2020}
# Retrieving value of an existing key
brand = car.get('brand', 'Unknown')
print("Brand:", brand)
# Retrieving value of a non-existing key with default value
color = car.get('color', 'Unknown')
print("Color:", color)
OutputBrand: Toyota
Color: Unknown
Explanation:
- get() method tries to fetch the value of the given key and if the key is found then the associated value is returned but if the key doesn't exist, the specified default value ('Unknown') is returned instead of raising a KeyError.
- In the example the key 'name' is present so the method returns 'Alice' but for the missing key 'city', the default 'Unknown' is returned.
Using setdefault() Method
setdefault() method works similarly to get() but with an important difference: if the key is not found in the dictionary then it will add the key with the provided default value. If the key exists, it simply returns the value associated with the key.
Python
car = {'brand': 'Toyota', 'year': 2020}
# Retrieving value of an existing key
brand = car.setdefault('brand', 'Unknown')
print("Brand:", brand)
# Retrieving value of a non-existing key with default value and adding it to the dictionary
color = car.setdefault('color', 'Unknown')
print("Color:", color)
print("Dictionary:", car)
OutputBrand: Toyota
Color: Unknown
Dictionary: {'brand': 'Toyota', 'year': 2020, 'color': 'Unknown'}
Explanation:
- setdefault() method retrieves the value of the given key just like get() however if the key is not present, it will insert the key with the specified default value into the dictionary.
- In this example the 'city' key doesn't exist so it is added to the dictionary with the value 'Unknown'. The 'name' key already exists, so it simply returns 'Alice'.
- This method is helpful when you want to ensure the key is present in the dictionary after accessing it.
Using collections.defaultdict()
defaultdict from Python’s collections module provides a more elegant way to handle missing keys with default values. When using defaultdict, you can specify a default factory function that will generate a default value when a key is not found.
Python
from collections import defaultdict
# Creating a defaultdict with a default value of 'Unknown'
car = defaultdict(lambda: 'Unknown', {'brand': 'Toyota', 'year': 2020})
# Retrieving value of an existing key
brand = car['brand']
print("Brand:", brand)
# Retrieving value of a non-existing key, default value is used
color = car['color']
print("Color:", color)
print("Dictionary:", dict(car))
OutputBrand: Toyota
Color: Unknown
Dictionary: {'brand': 'Toyota', 'year': 2020, 'color': 'Unknown'}
Explanation:
- defaultdict is initialized with a factory function lambda: 'Unknown'. This function is called whenever a missing key is accessed returning 'Unknown'.
- In the example the 'name' and 'age' keys already exist, so their values are returned as usual. The missing 'city' key is automatically added with the default value 'Unknown'.
- defaultdict allows for a more compact and efficient way to handle missing keys with a default value.
Using Dictionary Comprehension
With dictionary comprehension we can iterate over the existing dictionary and set default values for the missing keys by checking if they exist or not. This is particularly useful when you need to create or update dictionaries with default values based on certain conditions.
Python
car = {'brand': 'Toyota', 'year': 2020}
# Creating a new dictionary with default values for missing keys
keys = ['brand', 'year', 'color', 'model']
res = {key: car.get(key, 'Unknown') for key in keys}
print("Dictionary:", res)
OutputDictionary: {'brand': 'Toyota', 'year': 2020, 'color': 'Unknown', 'model': 'Unknown'}
Explanation:
- dictionary comprehension iterates through a list of keys (a) and checks if each key exists in the original dictionary person.
- If the key exists then it adds the corresponding value. If the key is missing, it assigns the default value 'Unknown'.
- This method is useful for creating a new dictionary with a specified set of keys and default values.
Similar Reads
Get Dictionary Value by Key - Python We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t
3 min read
Python - Alternate Default Key Value Sometimes, while working with Python Dictionaries, we can have problem in which we need to assign a particular value to a particular key, but in absence, require the similar's key's value but from different dictionary. This problem can have applications in domain of web development. Let's discuss ce
6 min read
Python - Decrement Dictionary value by K Sometimes, while working with dictionaries, we can have a use-case in which we require to decrement a particular keyâs value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Letâs disc
3 min read
Python Iterate Dictionary Key, Value In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Defaultdict in Python In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.Pythonfrom collections import defaultdict d = defaultdict(li
6 min read
Python Dictionary Add Value to Existing Key The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
2 min read