Python - Access Dictionary Items

What are Dictionary Items?

In Python, dictionary items are key-value pairs. You can access the value of a specific key using either:

  • Square brackets []
  • The get() method

Example 1: Access Using Square Brackets

car = {
 "brand": "Ford",
 "model": "Mustang",
 "year": 1964
}
print(car["model"])

Output:

Mustang

Explanation: We accessed the value of the key "model" using square brackets. If the key doesn’t exist, this method throws a KeyError.

Example 2: Access Using get() Method

car = {
 "brand": "Ford",
 "model": "Mustang",
 "year": 1964
}
print(car.get("year"))

Output:

1964

Explanation: The get() method safely returns the value for the key "year". If the key is missing, it returns None (or a default value if specified).

Example 3: Handling Missing Keys with get()

car = {
 "brand": "Ford",
 "model": "Mustang"
}
print(car.get("color", "Not specified"))

Output:

Not specified

Explanation: If the key "color" does not exist, get() returns the default value "Not specified" instead of throwing an error.

Example 4: Looping Through Dictionary Items

student = {
 "name": "Alice",
 "age": 22,
 "course": "Python"
}
for key in student:
   print(key, "=", student[key])

Output:

name = Alice
age = 22
course = Python

Explanation: This loop goes through each key in the dictionary and accesses its corresponding value using square brackets.

Example 5: Loop Using .items()

student = {
 "name": "Alice",
 "age": 22,
 "course": "Python"
}
for key, value in student.items():
   print(f"{key}: {value}")

Output:

name: Alice
age: 22
course: Python

Explanation: .items() returns key-value pairs which are unpacked in the loop directly.

Tip: Square Brackets vs get()

Feature[] Accessget() Method
Raises error?Yes, if key missingNo, returns None or default
Custom fallback?NoYes, via second argument
UsageSimple known keysSafer, optional fallback

Conclusion

You can access dictionary values using either square brackets or the safer get() method. Use square brackets when you're sure the key exists, and get() when you want to avoid errors or provide a fallback value.