Dictionaries
A dictionary stores key-value pairs, letting you look up values by a unique key instead of by position.
Creating Dictionaries
# Empty dictionary
empty = {}
# Dictionary with values
person = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}
Accessing Values
person = {"name": "Alice", "age": 20}
# Access by key
print(person["name"])
Output:
Alice
Use .get() to avoid errors when a key might not exist:
person = {"name": "Alice"}
print(person.get("name")) # Alice
print(person.get("age")) # None
print(person.get("age", 0)) # 0 (default value)
Adding and Updating Values
person = {"name": "Alice"}
# Add a new key
person["age"] = 20
# Update an existing key
person["age"] = 21
print(person)
Output:
{'name': 'Alice', 'age': 21}
Removing Items
person = {"name": "Alice", "age": 20, "major": "CS"}
# Remove and get the value
age = person.pop("age")
print(age) # 20
# Remove without getting the value
del person["major"]
print(person)
Output:
{'name': 'Alice'}
Checking if a Key Exists
person = {"name": "Alice", "age": 20}
if "name" in person:
print("Name found!")
if "email" not in person:
print("No email on file.")
Output:
Name found!
No email on file.
Looping Through Dictionaries
person = {"name": "Alice", "age": 20}
# Loop over keys
for key in person:
print(key)
# Loop over values
for value in person.values():
print(value)
# Loop over both (most common)
for key, value in person.items():
print(key + ": " + str(value))
Output:
name
age
Alice
20
name: Alice
age: 20
Nested Dictionaries
Dictionaries can contain other dictionaries:
students = {
"alice": {"age": 20, "grade": "A"},
"bob": {"age": 21, "grade": "B"}
}
print(students["alice"]["grade"])
Output:
A
Counting with Dictionaries
A common pattern is counting how many times items appear:
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for word in words:
if word in counts:
counts[word] = counts[word] + 1
else:
counts[word] = 1
print(counts)
Output:
{'apple': 3, 'banana': 2, 'cherry': 1}
Common Mistakes
Using a key that doesn't exist
person = {"name": "Alice"}
# Wrong - causes KeyError
print(person["age"])
# Right - use .get() for safety
print(person.get("age"))
Forgetting quotes around string keys
# Wrong
person = {name: "Alice"}
# Right
person = {"name": "Alice"}
Using a list as a key
# Wrong - lists can't be keys
data = {[1, 2]: "value"}
# Right - use a tuple instead
data = {(1, 2): "value"}