Accessing Values
-
This lesson teaches how to access values from a dictionary using keys in Python.
What Does "Accessing Values" Mean?
In a dictionary, data is stored as key : value pairs.
👉 Accessing values means retrieving the data stored inside a dictionary using its key.
Real-Life Example
Think of a dictionary as a contact list
To get Ravi’s number, you use his name (key).
Method 1: Using Square Brackets [ ]
Syntax
dictionary_name[key]
Access Value Using Key
This example retrieves the student's name using its key.
student = {
"name": "Amit",
"age": 20,
"course": "Python"
}
print(student["name"])
⚠ Important
If the key does not exist, Python gives an error:
print(student["marks"]) # KeyError
Method 2: Using get() Method
The get() method is a safe way to access dictionary values.
Syntax
dictionary_name.get(key)
Access Value Using get()
This example safely retrieves a value. If the key doesn't exist, it returns None.
student = {
"name": "Amit",
"age": 20
}
print(student.get("name"))
print(student.get("marks"))
Access Nested Dictionary
This example accesses values inside another dictionary.
student = {
"name": "Riya",
"marks": {
"math": 90,
"science": 88
}
}
print(student["marks"]["math"])
Difference: [ ] vs get()