Topic 9: Dictionaries (Key-Value Pairs)
A Dictionary is arguably Python's most powerful data structure. Instead of using numbers as indices (like 0, 1, 2), dictionaries use Keys. It works just like a real-world dictionary: you look up a "word" (the Key) to find its "definition" (the Value).
In other languages, this is often called a Map, Hash Table, or Associative Array.
1. Key Characteristics
Key-Value Pairs: Every item has a unique key and an associated value.
Unordered (pre-3.7): In modern Python (3.7+), they maintain insertion order.
Changeable: You can add or modify values using their keys.
Unique Keys: You cannot have two identical keys in one dictionary.
# Creating a dictionary for a student
student = {
"name": "Arjun",
"age": 21,
"courses": ["Python", "C++"],
"is_graduated": False
}
# Accessing values
print(f"Student Name: {student['name']}")
# Adding a new key-value pair
student["gpa"] = 3.8
# Updating a value
student["age"] = 22
# Getting all keys or values
print(f"Keys: {student.keys()}")
print(f"Values: {student.values()}")
# Iterating through a dictionary
for key, value in student.items():
print(f"{key}: {value}")Why use a Dictionary over a List?
Imagine you have 1,000 users.
In a List, to find "Arjun", you might have to check every single item until you find him ($O(n)$ complexity).
In a Dictionary, you simply ask for
users["Arjun"]and Python finds him instantly ($O(1)$ complexity).