Open In App

Get Dictionary Value by Key - Python

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

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 to access d['age'] then we get 25. But if we attempt to access d['country'], it results in a KeyError.

Using Bracket Notation ([])

The simplest way to access a value in a dictionary is by using bracket notation ([]) however if the key is not present, it raises a KeyError.

Python
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Accessing an existing key
print(d['age']) 

# Accessing a non-existent key (Raises KeyError)
#print(d['country'])  

Output
25

Explanation: d['age'] returns 25 because 'age' exists in the dictionary and d['country'] raises a KeyError since 'country' is not a key in d.

Using get() Method

get() method allows retrieving a value from a dictionary while providing a default value if the key is missing, this prevents KeyError and makes the code more robust.

Python
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Accessing an existing key
print(d.get('age'))  

# Accessing a non-existent key with a default value
print(d.get('country', 'Not Found'))  

Output
25
Not Found

Explanation: d.get('age') returns 25 since the key exists and d.get('country', 'Not Found') returns 'Not Found' instead of raising an error.

Using setdefault() Method

setdefault() method retrieves the value of a key if it exists otherwise inserts the key with a specified default value and returns that default.

Python
d = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Accessing an existing key
print(d.setdefault('age'))  

# Accessing a non-existent key and setting a default value
print(d.setdefault('country', 'USA')) 

print(d) 

Output
25
USA
{'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

Explanation: d.setdefault('age') returns 25 since the key exists and d.setdefault('country', 'USA') inserts 'country': 'USA' into the dictionary and returns 'USA'.

Using defaultdict from collections

defaultdict class from the collections module is an advanced dictionary type that provides a default value when a missing key is accessed, this prevents KeyError and is useful when handling multiple missing keys efficiently.

Python
from collections import defaultdict

# Creating a defaultdict with a default value of 'Unknown'
d = defaultdict(lambda: 'Unknown', {'name': 'geeks', 'age': 21, 'place': 'India'})

# Accessing value using bracket notation
val = d['place']
print("Country:", val)  

Output
Country: India

Explanation:

  • defaultdict(lambda: 'Unknown', {...}) initializes a dictionary where missing keys return 'Unknown' instead of raising an error.
  • d['place'] retrieves 'India' because the key exists.
  • If a key like 'country' were accessed (d['country']), it would return 'Unknown' instead of a KeyError.

Next Article
Practice Tags :

Similar Reads