Okay, you've seen that dictionaries store information using unique keys associated with values. This structure is highly efficient for looking up information when you know the key. Now, let's look at how you actually retrieve, change, add, or remove these key-value pairs.
The most direct way to get the value associated with a specific key is by using square brackets []
, similar to how you might access elements in a list by their index, but here you use the key instead.
# Example dictionary: Student grades
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Access Bob's grade
bob_grade = student_grades['Bob']
print(f"Bob's grade is: {bob_grade}") # Output: Bob's grade is: 92
# Access Alice's grade
alice_grade = student_grades['Alice']
print(f"Alice's grade is: {alice_grade}") # Output: Alice's grade is: 85
Be careful: If you try to access a key that doesn't exist in the dictionary using square brackets, Python will raise a KeyError
. This signals that the key you asked for wasn't found.
# Trying to access a non-existent key
# david_grade = student_grades['David'] # This line would cause a KeyError
# print(david_grade)
Running the commented-out line above would stop your program with an error message like: KeyError: 'David'
. In Chapter 9, you'll learn how to handle such errors gracefully, but for now, it's good to know they can happen.
Because accessing a missing key with []
causes an error, Python provides safer ways to retrieve values or check for keys.
get()
MethodThe dictionary's get()
method retrieves the value for a key just like square brackets, but with a significant difference: if the key is not found, it returns None
(a special Python value representing the absence of a value) instead of raising a KeyError
.
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Get Bob's grade (key exists)
bob_grade = student_grades.get('Bob')
print(f"Bob's grade (using get): {bob_grade}") # Output: Bob's grade (using get): 92
# Try to get David's grade (key does not exist)
david_grade = student_grades.get('David')
print(f"David's grade (using get): {david_grade}") # Output: David's grade (using get): None
You can also provide a default value to get()
as a second argument. If the key is not found, get()
will return this default value instead of None
.
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Get David's grade, return 0 if not found
david_grade = student_grades.get('David', 0)
print(f"David's grade (with default): {david_grade}") # Output: David's grade (with default): 0
# Get Alice's grade (key exists, default is ignored)
alice_grade = student_grades.get('Alice', 0)
print(f"Alice's grade (with default): {alice_grade}") # Output: Alice's grade (with default): 85
Using get()
is often preferred when you're not sure if a key exists and you want your program to continue running without interruption.
in
Another way to avoid KeyError
is to check if a key exists in the dictionary before trying to access it. You can do this using the in
operator, which returns True
if the key is present and False
otherwise.
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Check if 'Alice' is a key
if 'Alice' in student_grades:
print("Alice is in the dictionary.")
# Safe to access now
print(f"Alice's grade: {student_grades['Alice']}")
else:
print("Alice is not in the dictionary.")
# Check if 'David' is a key
if 'David' in student_grades:
print("David is in the dictionary.")
else:
print("David is not in the dictionary.") # This will be printed
Adding a new key-value pair or changing the value associated with an existing key uses the same simple assignment syntax with square brackets.
If the key you specify in the square brackets does not exist in the dictionary, a new key-value pair is added. If the key already exists, the value associated with that key is updated to the new value.
student_grades = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
print(f"Original grades: {student_grades}")
# Add a new student, David
student_grades['David'] = 88
print(f"After adding David: {student_grades}")
# Update Bob's grade
student_grades['Bob'] = 95
print(f"After updating Bob's grade: {student_grades}")
Output:
Original grades: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
After adding David: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
After updating Bob's grade: {'Alice': 85, 'Bob': 95, 'Charlie': 78, 'David': 88}
This makes dictionaries flexible for storing data that might change or grow over time.
Sometimes you need to remove items from a dictionary. Python offers a couple of ways to do this.
del
StatementThe del
statement removes a key-value pair based on its key.
student_grades = {'Alice': 85, 'Bob': 95, 'Charlie': 78, 'David': 88}
print(f"Grades before deletion: {student_grades}")
# Remove Charlie from the dictionary
del student_grades['Charlie']
print(f"Grades after deleting Charlie: {student_grades}")
Output:
Grades before deletion: {'Alice': 85, 'Bob': 95, 'Charlie': 78, 'David': 88}
Grades after deleting Charlie: {'Alice': 85, 'Bob': 95, 'David': 88}
Similar to accessing with []
, if you try to del
a key that doesn't exist, Python will raise a KeyError
.
pop()
MethodThe pop()
method also removes a key-value pair based on its key, but it does something extra: it returns the value that was associated with the removed key. This can be useful if you want to use the removed value immediately.
student_grades = {'Alice': 85, 'Bob': 95, 'David': 88}
print(f"Grades before pop: {student_grades}")
# Remove David and store his grade
davids_removed_grade = student_grades.pop('David')
print(f"Removed David's grade: {davids_removed_grade}") # Output: Removed David's grade: 88
print(f"Grades after popping David: {student_grades}") # Output: Grades after popping David: {'Alice': 85, 'Bob': 95}
If you try to pop()
a key that doesn't exist, it will raise a KeyError
, just like del
. However, pop()
allows you to provide a default value as a second argument. If the key isn't found, pop()
returns the default value instead of raising an error.
student_grades = {'Alice': 85, 'Bob': 95}
# Try to pop 'Charlie', provide a default value
result = student_grades.pop('Charlie', 'Not Found')
print(f"Result of popping Charlie: {result}") # Output: Result of popping Charlie: Not Found
print(f"Grades remain unchanged: {student_grades}") # Output: Grades remain unchanged: {'Alice': 85, 'Bob': 95}
popitem()
There's also a method called popitem()
which removes and returns an arbitrary (key, value) pair from the dictionary. Before Python 3.7, it removed a truly random item. In Python 3.7+, it follows Last-In, First-Out (LIFO) order, removing the most recently added item. This is less commonly used for beginners than del
or pop(key)
.
student_grades = {'Alice': 85, 'Bob': 95}
student_grades['Eve'] = 90 # Add Eve last
# Remove and return the last added item (in Python 3.7+)
last_item = student_grades.popitem()
print(f"Removed item: {last_item}") # Output: Removed item: ('Eve', 90)
print(f"Dictionary after popitem: {student_grades}") # Output: Dictionary after popitem: {'Alice': 85, 'Bob': 95}
You now have the essential tools to interact with the data stored in dictionaries: accessing values (safely or directly), adding new pairs, updating existing ones, and removing pairs when necessary. These operations are fundamental to using dictionaries effectively in your programs.
© 2025 ApX Machine Learning