The Wayback Machine - https://web.archive.org/web/20250116085645/https://www.geeksforgeeks.org/python-get-dictionary-value-by-key/
Open In App

Python Get Dictionary Value by Key

Last Updated : 09 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dictionaries are a fundamental data structure in Python, allowing you to store and retrieve data using key-value pairs. Retrieving a value from a dictionary by its key is a common operation in many Python programs. In this article, we will explore five simple and commonly used methods to get a dictionary value by its key in Python.

Python
# Creating a sample dictionary
d = {'name': 'geeks', 'age': 21, 'place': 'India'}

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



Python Get Dictionary Value by Key - Using get() Method

We can use get() method to retrieve the value associated with the key 'name' safely, and the result is printed as "Name: geeks".

Python
# Creating a sample dictionary
d = {'name': 'geeks', 'age': 21, 'place': 'India'}

# Using get() method
val = d.get('name')
print("Name:", val)

Output
Name: geeks

Python Get Dictionary Value by Key - Using setdefault() Method

We can use setdefault() method to retrieve the value associated with the key 'name' and set a default value ('Default Name') if the key is not found. Additionally, `setdefault()` is used for a key ('country') not present in the dictionary, setting a default value ('Unknown').

Python
# Creating a sample dictionary
d = {'name': 'geeks', 'age': 21, 'place': 'India'}

# Using setdefault() method
val = d.setdefault('name', 'Default Name')
print("Name:", val)

# Using setdefault() for a key not present in the dictionary
country_value = d.setdefault('country', 'Unknown')
print("Country:", country_value)

Output
Name: geeks
Country: Unknown

Python Get Dictionary Value by Key - Using Collections Module

In this example, we have created a defaultdict from collections module with a default value of 'Unknown'. The value associated with the key 'place' is then accessed using bracket notation, and the result is printed as "Country: India".

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
country_value = d['place']
print("Country:", country_value)

Output
Country: India

Learn Python from scratch with our Python Full Course Online, designed for beginners and advanced learners alike. Master everything from Python basics to advanced python concepts with hands-on practice and projects.


Take the Three 90 Challenge! Finish 90% of the course in 90 days, and receive a 90% refund. Stay on track, keep progressing, and get rewarded for your hard work.
Start today and become a Python pro!


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg