Access Dictionary Items
Accessing dictionary items is a core Python skill, because dictionaries are used everywhere for structured and real-world data.
Unlike lists or tuples, dictionary items are accessed using keys, not indexes.
This topic explains all correct ways to access dictionary items, from basic to advanced.
Access Dictionary Items Using Keys
The most direct way to access a value is by using its key.
python
student = {
"name": "Jayesh",
"age": 25,
"course": "Python"
}
print(student["name"])
If the key does not exist, Python raises an error.
python
# print(student["salary"]) # KeyError
Access Dictionary Items Using get() (Recommended)
The
get() method is a safe way to access values.python
print(student.get("age"))
python
print(student.get("salary")) # None
You can provide a default value.
python
print(student.get("salary", 0))
Access All Keys
python
keys = student.keys()
print(keys)
python
for key in student.keys():
print(key)
Access All Values
python
values = student.values()
print(values)
python
for value in student.values():
print(value)
Access Key–Value Pairs
Use
items() to access both key and value together.python
for key, value in student.items():
print(key, value)
Check If Key Exists
Before accessing, you can check if a key exists.
python
if "name" in student:
print(student["name"])
Access Nested Dictionary Items
python
students = {
"student1": {
"name": "Amit",
"age": 20
},
"student2": {
"name": "Riya",
"age": 22
}
}
print(students["student1"]["name"])
Access Nested Dictionary Using get()
python
print(students.get("student1", {}).get("age"))
This avoids errors if any key is missing.
Access Dictionary Items Using Loop
Keys Only
python
for key in student:
print(key, student[key])
Values Only
python
for value in student.values():
print(value)
Key–Value Together
python
for key, value in student.items():
print(f"{key}: {value}")
Access Dictionary Items Using Index (Not Allowed)
python
# student[0] # TypeError
Dictionaries do not support index-based access.
Convert Dictionary for Indexed Access
If index-based access is needed.
python
keys = list(student.keys())
print(keys[0])
python
values = list(student.values())
print(values[0])
Common Mistakes
Accessing Missing Key Directly
python
# print(student["salary"]) # KeyError
Assuming Order Before Python 3.7
python
# Order was not guaranteed before Python 3.7
Best Practices
- Use
get()for safe access - Check key existence using
in - Use
items()for loops - Avoid index-based access
- Use nested
get()for deep dictionaries
Summary
- Dictionary values are accessed using keys
get()prevents runtime errorskeys(),values(),items()provide structured access- Nested dictionaries require chained access
- Dictionaries do not support indexing