Python Access Dictionary Items
You can read values from a dictionary either by using square brackets with a key or by calling the safer get() method.
Accessing values by key
To fetch a value, place its key inside square brackets after the dictionary name. If the key does not exist, Python raises a KeyError, which stops the program unless you handle it.
Bracket access
car = {"brand": "Toyota", "model": "Corolla", "year": 2021}
print(car["brand"])
print(car["year"])Using get() for safe lookups
The get() method returns the value for a key, but instead of crashing on a missing key it returns None (or a default you supply). This makes it a good choice when you are not certain a key is present.
get() with a default value
car = {"brand": "Toyota", "model": "Corolla", "year": 2021}
print(car.get("model"))
print(car.get("color")) # None
print(car.get("color", "unknown")) # unknownNote: Reaching for a missing key with square brackets raises KeyError. Prefer get() when a key might be absent, or check membership first with the 'in' keyword.
Views: keys, values, and items
Three methods let you inspect the whole dictionary at once. They return view objects that stay in sync with the dictionary, so any later change is reflected automatically.
Checking if a key exists
car = {"brand": "Toyota", "model": "Corolla", "year": 2021}
if "model" in car:
print("Model is", car["model"])
print("color" in car) # False- Use brackets when you are sure the key exists.
- Use get() when a key may be missing and you want a fallback.
- Use 'in' to test for a key before accessing it.