Dictionaries
Dictionaries
Dictionaries store data as key-value pairs. They're perfect for when you want to look up values by a unique identifier.
Creating Dictionaries
# Empty dictionary
empty = {}
# With values
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Using dict() constructor
person = dict(name="Alice", age=30, city="New York")
Accessing Values
person = {"name": "Alice", "age": 30, "city": "New York"}
# Using brackets
print(person["name"]) # "Alice"
# Using get() - safer, returns None if key doesn't exist
print(person.get("name")) # "Alice"
print(person.get("country")) # None
print(person.get("country", "USA")) # "USA" (default value)
Tip: Use
get()when the key might not exist to avoidKeyError.
Modifying Dictionaries
person = {"name": "Alice", "age": 30}
# Add or update a key
person["city"] = "New York" # Add new key
person["age"] = 31 # Update existing key
# Remove a key
del person["city"]
# Pop - remove and return value
age = person.pop("age")
print(age) # 31
Dictionary Methods
| Method | Description |
|---|---|
keys() |
Returns all keys |
values() |
Returns all values |
items() |
Returns key-value pairs as tuples |
get(key, default) |
Get value with default if missing |
pop(key) |
Remove and return value |
update(dict2) |
Merge another dictionary |
clear() |
Remove all items |
person = {"name": "Alice", "age": 30, "city": "NYC"}
print(list(person.keys())) # ["name", "age", "city"]
print(list(person.values())) # ["Alice", 30, "NYC"]
print(list(person.items())) # [("name", "Alice"), ...]
Looping Over Dictionaries
person = {"name": "Alice", "age": 30, "city": "NYC"}
# Loop over keys
for key in person:
print(key)
# Loop over values
for value in person.values():
print(value)
# Loop over both
for key, value in person.items():
print(f"{key}: {value}")
Nested Dictionaries
students = {
"alice": {
"grade": "A",
"age": 20
},
"bob": {
"grade": "B",
"age": 21
}
}
# Access nested values
print(students["alice"]["grade"]) # "A"
Dictionary Comprehensions
# Create a dictionary of squares
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filter while creating
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Common Use Cases
Counting occurrences
text = "hello world"
char_count = {}
for char in text:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Grouping data
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"}
]
by_grade = {}
for student in students:
grade = student["grade"]
if grade not in by_grade:
by_grade[grade] = []
by_grade[grade].append(student["name"])
print(by_grade)
# {"A": ["Alice", "Charlie"], "B": ["Bob"]}
When to use dictionaries: Use them when you need fast lookups by a unique key, or when data naturally has key-value relationships.