While lists and tuples are great for ordered sequences, sometimes you need to associate pieces of data together without relying on a specific order. Imagine a real-world dictionary: you look up a word (the "key") to find its definition (the "value"). Python's dictionaries work similarly, storing data as key-value pairs.
Dictionaries are incredibly useful when you need to retrieve data based on a specific identifier rather than its position in a sequence. They are defined using curly braces {}
.
You create a dictionary by enclosing comma-separated key-value pairs within curly braces {}
. Each pair consists of a key, followed by a colon :
, and then the corresponding value.
# An empty dictionary
empty_dict = {}
# A dictionary storing student grades
student_grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
print(student_grades)
# Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Keys can be different immutable types (strings, numbers, tuples)
mixed_keys = {
"name": "Example Item",
101: "Item ID",
("x", "y"): "Coordinates"
}
print(mixed_keys)
# Output: {'name': 'Example Item', 101: 'Item ID', ('x', 'y'): 'Coordinates'}
Important Rules for Keys:
You access the value associated with a specific key using square brackets []
, similar to how you access elements in a list by index, but using the key instead.
student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}
# Get Bob's grade
bobs_grade = student_grades["Bob"]
print(f"Bob's grade is: {bobs_grade}")
# Output: Bob's grade is: 92
# Trying to access a non-existent key causes an error
# print(student_grades["David"]) # This would raise a KeyError
If you try to access a key that doesn't exist in the dictionary, Python will raise a KeyError
. We'll see how to handle potential errors like this in a later chapter on exception handling. A safer way to get a value if you're unsure whether the key exists is using the get()
method, which returns None
(or a default value you specify) if the key is not found, instead of raising an error.
student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}
# Get Alice's grade using get()
alice_grade = student_grades.get("Alice")
print(f"Alice's grade (using get): {alice_grade}")
# Output: Alice's grade (using get): 85
# Try to get David's grade (doesn't exist)
david_grade = student_grades.get("David")
print(f"David's grade (using get): {david_grade}")
# Output: David's grade (using get): None
# Provide a default value if the key is missing
eve_grade = student_grades.get("Eve", "Not Found")
print(f"Eve's grade (using get with default): {eve_grade}")
# Output: Eve's grade (using get with default): Not Found
Adding a new key-value pair or modifying the value associated with an existing key is straightforward. You use the square bracket notation on the left side of an assignment statement.
student_grades = {"Alice": 85, "Bob": 92}
print(f"Original grades: {student_grades}")
# Add a new student
student_grades["Charlie"] = 78
print(f"After adding Charlie: {student_grades}")
# Update Bob's grade
student_grades["Bob"] = 95
print(f"After updating Bob: {student_grades}")
Output:
Original grades: {'Alice': 85, 'Bob': 92}
After adding Charlie: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
After updating Bob: {'Alice': 85, 'Bob': 95, 'Charlie': 78}
If the key ("Charlie") doesn't exist, a new pair is added. If the key ("Bob") already exists, its corresponding value is updated.
You can remove key-value pairs using the del
keyword or the pop()
method.
student_grades = {"Alice": 85, "Bob": 95, "Charlie": 78}
print(f"Initial dictionary: {student_grades}")
# Remove Charlie using del
del student_grades["Charlie"]
print(f"After deleting Charlie: {student_grades}")
# Remove Bob using pop() and get the removed value
bobs_removed_grade = student_grades.pop("Bob")
print(f"Removed Bob's grade: {bobs_removed_grade}")
print(f"Dictionary after popping Bob: {student_grades}")
Output:
Initial dictionary: {'Alice': 85, 'Bob': 95, 'Charlie': 78}
After deleting Charlie: {'Alice': 85, 'Bob': 95}
Removed Bob's grade: 95
Dictionary after popping Bob: {'Alice': 85}
Using del
simply removes the item. The pop()
method removes the item and returns its value, which can be useful. If you try to del
or pop
a key that doesn't exist, you'll get a KeyError
.
Dictionaries come with several useful methods:
keys()
: Returns a view object displaying a list of all the keys.values()
: Returns a view object displaying a list of all the values.items()
: Returns a view object displaying a list of key-value tuple pairs.len()
: (Not a method, but a built-in function) Returns the number of key-value pairs.in
: (Operator) Checks if a key exists in the dictionary.student_grades = {"Alice": 85, "Bob": 95, "Charlie": 78}
print(f"Keys: {student_grades.keys()}")
print(f"Values: {student_grades.values()}")
print(f"Items: {student_grades.items()}")
print(f"Number of students: {len(student_grades)}")
# Check if 'Alice' is in the dictionary
if "Alice" in student_grades:
print("Alice is in the grades dictionary.")
# Check if 'David' is in the dictionary
if "David" not in student_grades:
print("David is not in the grades dictionary.")
Output:
Keys: dict_keys(['Alice', 'Bob', 'Charlie'])
Values: dict_values([85, 95, 78])
Items: dict_items([('Alice', 85), ('Bob', 95), ('Charlie', 78)])
Number of students: 3
Alice is in the grades dictionary.
David is not in the grades dictionary.
Note that keys()
, values()
, and items()
return "view objects". These views reflect changes made to the dictionary. You can iterate over these views directly in loops (which we covered in the previous chapter) or convert them to lists if needed using list()
.
A dictionary maps unique, immutable keys to corresponding values.
Dictionaries provide a flexible way to structure data when the order isn't the primary concern, but fast lookup based on an identifier is. They are one of the most frequently used data structures in Python.
© 2025 ApX Machine Learning