Skip to content

Python Access Dictionaries

Syntax

You can access dictionary values using their keys or by using the get() method.

# Accessing values by key
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
name = person["name"] # "Alice"
age = person["age"] # 25
# Using the get() method
city = person.get("city") # "New York"
country = person.get("country", "USA") # Returns "USA" if "country" key is not found

Example

# Accessing values from a dictionary of student details
student = {
"name": "John",
"grade": "A",
"age": 20
}
print(f"Student Name: {student['name']}")
print(f"Grade: {student.get('grade')}")
print(f"Major: {student.get('major', 'Undeclared')}")