guidebeginner15 min
Dictionaries: Key-Value Pairs
Store data with meaningful keys instead of numeric indices. Perfect for structured information.
Prerequisites
Last updated: Jan 28, 2026
Dictionaries store data as key-value pairs. Instead of accessing items by position (like lists), you access them by a meaningful key. Think of it like a real dictionary: you look up a word (key) to find its definition (value).
Creating Dictionaries
python
# Basic dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Empty dictionary
empty = {}
# Using dict()
also_empty = dict()
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'New York'}Accessing Values
python
person = {"name": "Alice", "age": 25, "city": "New York"}
# Access by key
print(person["name"]) # Alice
print(person["age"]) # 25
# Using get() - safer, returns None if key doesn't exist
print(person.get("name")) # Alice
print(person.get("country")) # None (no error)
print(person.get("country", "Unknown")) # "Unknown" (default value)
# Direct access to missing key causes error
# print(person["country"]) # KeyError!Modifying Dictionaries
python
person = {"name": "Alice", "age": 25}
# Change a value
person["age"] = 26
print(person) # {'name': 'Alice', 'age': 26}
# Add new key-value pair
person["city"] = "New York"
print(person) # {'name': 'Alice', 'age': 26, 'city': 'New York'}
# Remove a key
del person["city"]
print(person) # {'name': 'Alice', 'age': 26}
# Remove and return value
age = person.pop("age")
print(age) # 26
print(person) # {'name': 'Alice'}Checking Keys
python
person = {"name": "Alice", "age": 25}
# Check if key exists
print("name" in person) # True
print("country" in person) # False
# Get all keys, values, or both
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Alice', 25])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25)])Looping Over Dictionaries
python
person = {"name": "Alice", "age": 25, "city": "New York"}
# Loop over keys (default)
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}")
# name: Alice
# age: 25
# city: New YorkNested Dictionaries
Dictionaries can contain other dictionaries:
python
users = {
"alice": {
"age": 25,
"email": "alice@email.com"
},
"bob": {
"age": 30,
"email": "bob@email.com"
}
}
# Access nested values
print(users["alice"]["email"]) # alice@email.com
# Modify nested values
users["alice"]["age"] = 26Practical Example: Word Counter
python
text = "the quick brown fox jumps over the lazy dog"
words = text.split() # Split into list of words
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(word_counts)
# {'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, ...}
# Find most common word
most_common = max(word_counts, key=word_counts.get)
print(f"Most common: '{most_common}' ({word_counts[most_common]} times)")When to Use Lists vs Dictionaries
- Use lists when: Order matters, items are similar, you access by position
- Use dictionaries when: You need to look up by name/key, data has structure
python
# List: collection of similar things
scores = [85, 92, 78, 95, 88]
# Dictionary: structured record
student = {
"name": "Alice",
"scores": [85, 92, 78],
"grade": "A"
}
# List of dictionaries: collection of records
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"}
]Practice
- Create a dictionary representing a book (title, author, year, pages)
- Write a function that inverts a dictionary (swap keys and values)
- Create a phone book dictionary and write functions to add, remove, and look up contacts
- Count the frequency of each character in a string using a dictionary
- Merge two dictionaries together