Open In App

Python Dict Get Value by Key Default

Last Updated : 04 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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)

Output
Brand: 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)

Output
Brand: 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))

Output
Brand: 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)

Output
Dictionary: {'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.

Practice Tags :

Similar Reads