Lists are great for storing ordered collections of items, but sometimes you need a different way to organize data. What if you want to store information about a person—their name, age, email, and city—and access each piece by name rather than position? This is where dictionaries come in.
Dictionaries are Python's way of storing data as key-value pairs. Instead of accessing items by their position (like in lists), you access them by their key (a name or identifier). Dictionaries are perfect for representing real-world objects, storing configuration settings, and organizing related data. By the end of this lesson, you'll understand when and how to use dictionaries effectively.
What You'll Learn
- How to create and initialize dictionaries
- Accessing and modifying dictionary values
- Adding and removing key-value pairs
- Dictionary methods and operations
- Iterating over dictionaries
- Nested dictionaries for complex data
- When to use dictionaries vs. lists
- Best practices for dictionary usage
Creating Dictionaries
A dictionary is created using curly braces {} with key-value pairs separated by colons. Each key is unique and maps to a value:
# Creating dictionaries
person = {
"name": "Daniel",
"age": 30,
"city": "London",
"email": "daniel@example.com"
}
# Empty dictionary
empty = {}
# Dictionary with different data types
mixed = {
"name": "Python",
"version": 3.11,
"is_popular": True,
"features": ["simple", "readable", "powerful"]
}
print(person)
print(mixed)
You can also create dictionaries using the dict() function:
# Creating dictionaries with dict()
person = dict(name="Daniel", age=30, city="London")
print(person) # {'name': 'Daniel', 'age': 30, 'city': 'London'}
Accessing Dictionary Values
You access dictionary values using their keys, similar to how you access list elements by index:
# Accessing dictionary values
person = {
"name": "Daniel",
"age": 30,
"city": "London"
}
# Using square brackets
print(person["name"]) # "Daniel"
print(person["age"]) # 30
# Using get() method (safer - returns None if key doesn't exist)
print(person.get("name")) # "Daniel"
print(person.get("email")) # None (key doesn't exist)
print(person.get("email", "N/A")) # "N/A" (default value)
The get() method is safer than using square brackets because it won't raise an error if the key doesn't exist:
# Square brackets raise error if key doesn't exist
# print(person["email"]) # KeyError!
# get() returns None or default value
print(person.get("email")) # None
print(person.get("email", "N/A")) # "N/A"
Modifying Dictionaries
Dictionaries are mutable, so you can add, modify, or remove key-value pairs:
# Modifying dictionaries
person = {"name": "Daniel", "age": 30}
# Adding new key-value pairs
person["city"] = "London"
person["email"] = "daniel@example.com"
print(person)
# Modifying existing values
person["age"] = 31
print(person)
# Removing key-value pairs
del person["email"] # Remove using del
print(person)
removed = person.pop("city") # Remove and return value
print(f"Removed: {removed}")
print(person)
Dictionary Methods
Python provides many useful methods for working with dictionaries:
# Common dictionary methods
person = {
"name": "Daniel",
"age": 30,
"city": "London",
"email": "daniel@example.com"
}
# Getting keys, values, and items
print(person.keys()) # dict_keys(['name', 'age', 'city', 'email'])
print(person.values()) # dict_values(['Daniel', 30, 'London', 'daniel@example.com'])
print(person.items()) # dict_items([('name', 'Daniel'), ('age', 30), ...])
# Checking if key exists
print("name" in person) # True
print("phone" in person) # False
# Getting all keys as a list
keys_list = list(person.keys())
print(keys_list)
# Copying dictionaries
person_copy = person.copy()
print(person_copy)
Iterating Over Dictionaries
You can iterate over dictionaries in several ways, depending on what you need:
# Iterating over dictionaries
person = {
"name": "Daniel",
"age": 30,
"city": "London"
}
# Iterate over keys (default)
for key in person:
print(f"{key}: {person[key]}")
# Iterate over keys explicitly
for key in person.keys():
print(key)
# Iterate over values
for value in person.values():
print(value)
# Iterate over key-value pairs (most common)
for key, value in person.items():
print(f"{key}: {value}")
Here's a practical example:
# Processing multiple people's information
people = {
"Alice": {"age": 25, "city": "New York"},
"Bob": {"age": 30, "city": "London"},
"Charlie": {"age": 35, "city": "Tokyo"}
}
# Display all information
for name, info in people.items():
print(f"{name} is {info['age']} years old and lives in {info['city']}")
Nested Dictionaries
Dictionaries can contain other dictionaries, lists, or any data type. This allows you to represent complex, real-world data:
# Nested dictionaries
students = {
"student1": {
"name": "Alice",
"grades": [85, 90, 88],
"contact": {
"email": "alice@example.com",
"phone": "123-456-7890"
}
},
"student2": {
"name": "Bob",
"grades": [92, 87, 91],
"contact": {
"email": "bob@example.com",
"phone": "098-765-4321"
}
}
}
# Accessing nested data
print(students["student1"]["name"]) # "Alice"
print(students["student1"]["grades"][0]) # 85
print(students["student1"]["contact"]["email"]) # "alice@example.com"
# Modifying nested data
students["student1"]["grades"].append(95)
print(students["student1"]["grades"])
Dictionaries vs. Lists
Understanding when to use dictionaries versus lists is important:
Use Lists when:
- Order matters
- You need to access items by position
- Items are similar in nature (all names, all numbers)
- You need to maintain duplicates
Use Dictionaries when:
- You need to access items by name/key
- Data has labels or attributes
- Each item is unique (like a person's information)
- You're representing real-world objects
# Lists: ordered collection of similar items
fruits = ["apple", "banana", "orange"]
# Dictionaries: labeled collection of related data
person = {
"name": "Daniel",
"age": 30,
"city": "London"
}
Practical Example: Student Management System
Let's create a practical example that combines everything we've learned:
# Student management system using dictionaries
students = {}
# Add students
students["alice"] = {
"name": "Alice",
"age": 20,
"grades": [85, 90, 88],
"email": "alice@university.edu"
}
students["bob"] = {
"name": "Bob",
"age": 21,
"grades": [92, 87, 91],
"email": "bob@university.edu"
}
# Calculate and display averages
for student_id, info in students.items():
grades = info["grades"]
average = sum(grades) / len(grades)
print(f"{info['name']}: {average:.2f}")
# Update a student's grade
students["alice"]["grades"].append(95)
print(f"Alice's updated grades: {students['alice']['grades']}")
# Find student with highest average
best_student = None
best_average = 0
for student_id, info in students.items():
grades = info["grades"]
average = sum(grades) / len(grades)
if average > best_average:
best_average = average
best_student = info["name"]
print(f"Best student: {best_student} with average {best_average:.2f}")
Try It Yourself
Practice working with dictionaries using these exercises:
-
Contact Book: Create a program that stores contacts as dictionaries with name, phone, and email. Allow users to add, view, and search for contacts.
-
Inventory System: Build a simple inventory system using dictionaries. Each item should have a name, quantity, and price. Calculate the total value of all items.
-
Grade Book: Create a grade book using nested dictionaries. Store multiple students, each with their name and a list of test scores. Calculate each student's average grade.
-
User Profile: Design a user profile system that stores user information (username, email, preferences) and allows updating individual fields.
These exercises will help you become comfortable with dictionaries and understand when they're the right choice for organizing data.
Summary
In this lesson, you've learned how to work with dictionaries—Python's key-value data structure. You now understand how to create dictionaries, access and modify values, use dictionary methods, iterate over dictionaries, and work with nested dictionaries for complex data.
Dictionaries are perfect for storing labeled, related data where you need to access values by name rather than position. They're essential for representing real-world objects, storing configuration data, and organizing information in a meaningful way.
Remember that dictionary keys must be unique and immutable (strings, numbers, or tuples). Values can be any data type, including other dictionaries or lists. The get() method is safer than square brackets when you're not sure if a key exists.
What's Next?
In the next lesson, we'll explore functions—reusable blocks of code that perform specific tasks. Functions allow you to organize your code, avoid repetition, and make your programs more modular and maintainable. You'll learn how to define functions, pass arguments, return values, and use functions to structure your programs effectively.