Get Dictionary Value by Key - Python
Last Updated :
04 Feb, 2025
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'])
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'))
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)
Output25
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)
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.
Similar Reads
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
Python Update Dictionary Value by Key A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can
3 min read
Get Total Keys in Dictionary - Python We are given a dictionary and our task is to count the total number of keys in it. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} then the output will be 4 as the total number of keys in this dictionary is 4.Using len() with dictThe simplest way to count the total numb
2 min read
Python Dict Get Value by Key Default 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
4 min read
Get Index of Values in Python Dictionary Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read