Accessing Dictionary Values
Once you have a dictionary, you need to get values out of it. Unlike lists where you use numeric indexes, dictionaries use keys.
Reading Values
Use square brackets with the key name:
person = {"name": "Alice", "age": 30}
print(person["name"]) # Alice
print(person["age"]) # 30
This looks similar to list indexing, but instead of a number, you provide the key string.
What If the Key Doesn't Exist?
If you try to access a key that isn't in the dictionary, Python raises a KeyError:
person = {"name": "Alice", "age": 30}
print(person["email"]) # KeyError: 'email'
This crashes your program unless you handle the error.
Safe Access With get()
The get() method provides a safer alternative. If the key doesn't exist, it returns None instead of crashing:
person = {"name": "Alice", "age": 30}
print(person.get("email")) # None (no error)
You can also provide a default value:
print(person.get("email", "N/A")) # N/A
This is perfect when you're not sure if a key exists and want to handle missing data gracefully.
Updating Values
To change an existing value, assign to its key:
person = {"name": "Alice", "age": 30}
person["age"] = 31
print(person) # {'name': 'Alice', 'age': 31}
Adding New Keys
Adding a new key-value pair uses the same syntax:
person = {"name": "Alice", "age": 30}
person["city"] = "Boston"
print(person) # {'name': 'Alice', 'age': 30, 'city': 'Boston'}
If the key exists, it updates. If it doesn't, it adds.
Checking If a Key Exists
Use the in operator to check before accessing:
person = {"name": "Alice", "age": 30}
if "email" in person:
print(person["email"])
else:
print("No email on file")
Removing Keys
Use del to remove a key-value pair:
person = {"name": "Alice", "age": 30, "city": "Boston"}
del person["city"]
print(person) # {'name': 'Alice', 'age': 30}
Or use pop() to remove and get the value:
city = person.pop("city") # Returns "Boston" and removes the key