Lesson 3 • Intermediate
Dictionaries in Python
Store and access data using key-value pairs for fast and organized data management.
What You'll Learn in This Lesson
- ✓What a dictionary is and how key-value pairs work
- ✓The difference between lists and dictionaries — when to use which
- ✓How to safely access values using .get() vs square brackets
- ✓How to add, update, and delete key-value pairs
- ✓How to loop through keys, values, and items
- ✓Nested dictionaries and real-world use cases
1. What Are Dictionaries?
A dictionary stores data in key-value pairs. Instead of accessing items by position (like lists), you access them by a unique key name.
Key Characteristics
- Key-value pairs — Each item has a name (key) and data (value)
- Fast lookups — Access any value instantly by its key
- Unique keys — Each key can only appear once
- Mutable — You can add, change, or remove items
- Ordered — Maintains insertion order (Python 3.7+)
2. Lists vs Dictionaries
Understanding when to use each:
| Feature | List | Dictionary |
|---|---|---|
| Access by | Index (0, 1, 2...) | Key name |
| Syntax | [item1, item2] | {key: value} |
| Best for | Ordered collections | Named/labeled data |
| Example use | List of names | User profile info |
fruits = ["apple", "banana"] print(fruits[0]) # apple
person = {"name": "Alice"}
print(person["name"]) # Alice3. Creating Dictionaries
| Method | Example | Description |
|---|---|---|
| Empty dictionary | my_dict = {} | Start with nothing |
| With data | {"key": "value"} | Key-value pairs |
| Using dict() | dict(name="Alice") | Constructor function |
Try It: Creating Dictionaries
Different ways to create dictionaries
# Different ways to create dictionaries
# Empty dictionary
my_dict = {}
print("Empty:", my_dict)
# Dictionary with data
person = {
"name": "Alice",
"age": 25,
"city": "London"
}
print("Person:", person)
# Using dict() constructor
info = dict(name="Bob", age=30, job="Developer")
print("Info:", info)
# Mixed value types
product = {
"id": 101,
"name": "Laptop",
"price": 999.99,
"in_stock": True
}
print("Product:", product)4. Accessing Values
There are two ways to access dictionary values:
| Method | Syntax | If Key Missing |
|---|---|---|
| Square brackets | dict["key"] | KeyError (crashes) |
| .get() method | dict.get("key") | Returns None (safe) |
| .get() with default | dict.get("key", "default") | Returns your default |
Try It: Accessing Values
Two ways to get dictionary values
person = {"name": "Alice", "age": 25}
# Method 1: Square brackets (fast but risky)
print("Name:", person["name"])
# Method 2: .get() method (safe)
print("Age:", person.get("age"))
# .get() with missing key
print("Email:", person.get("email")) # Returns None
print("Email:", person.get("email", "N/A")) # Returns "N/A"
# Square brackets with missing key would crash:
# print(person["email"]) # KeyError!.get() when you are not 100% sure the key exists. It prevents your program from crashing!5. Adding and Changing Items
Dictionaries are mutable — you can add new key-value pairs or update existing ones using the same syntax:
Try It: Adding and Changing
Add new items or update existing ones
person = {"name": "Alice"}
print("Start:", person)
# Add new key-value pair
person["age"] = 25
print("After adding age:", person)
# Add another
person["city"] = "London"
print("After adding city:", person)
# Change existing value
person["age"] = 26
print("After changing age:", person)
# Add multiple with .update()
person.update({"job": "Developer", "country": "UK"})
print("After update:", person)6. Removing Items
| Method | What It Does | Example |
|---|---|---|
| del dict["key"] | Delete a specific key | del person["age"] |
| .pop("key") | Remove and return the value | age = person.pop("age") |
| .popitem() | Remove last inserted item | last = person.popitem() |
| .clear() | Remove all items | person.clear() |
Try It: Removing Items
Different ways to remove dictionary items
person = {"name": "Alice", "age": 25, "city": "London"}
print("Start:", person)
# del - delete by key
del person["city"]
print("After del:", person)
# pop - remove and get the value
age = person.pop("age")
print(f"Popped age: {age}")
print("After pop:", person)
# pop with default (safe)
job = person.pop("job", "Not found")
print(f"Popped job: {job}")7. Checking if a Key Exists
Use in to check if a key exists before accessing it:
Try It: Checking Keys
Check if keys exist before accessing
person = {"name": "Alice", "age": 25}
# Check if key exists
if "name" in person:
print("Name found:", person["name"])
if "email" in person:
print("Email:", person["email"])
else:
print("Email not found")
# Check if key does NOT exist
if "phone" not in person:
print("Phone number not stored")
# Practical pattern: safe access
key = "city"
if key in person:
print(f"{key}: {person[key]}")
else:
print(f"{key} is not in the dictionary")8. Looping Through Dictionaries
| Loop Type | What You Get | Syntax |
|---|---|---|
| Keys only | Each key | for key in dict: |
| Values only | Each value | for val in dict.values(): |
| Both | Key and value | for key, val in dict.items(): |
Try It: Looping
Iterate over keys, values, or both
person = {"name": "Alice", "age": 25, "city": "London"}
# Loop through keys (default)
print("Keys:")
for key in person:
print(f" {key}")
# Loop through values
print("\nValues:")
for value in person.values():
print(f" {value}")
# Loop through key-value pairs (most common)
print("\nKey-Value pairs:")
for key, value in person.items():
print(f" {key}: {value}")9. Useful Dictionary Methods
| Method | What It Returns | Example |
|---|---|---|
| .keys() | All keys | person.keys() |
| .values() | All values | person.values() |
| .items() | All key-value pairs | person.items() |
| .get(key) | Value or None | person.get("name") |
| .update(dict2) | Merges dict2 into dict | person.update({...}) |
| .copy() | A copy of the dict | new = person.copy() |
| len(dict) | Number of pairs | len(person) |
Try It: Dictionary Methods
Common dictionary operations
person = {"name": "Alice", "age": 25, "city": "London"}
# Get all keys
print("Keys:", list(person.keys()))
# Get all values
print("Values:", list(person.values()))
# Get all items as tuples
print("Items:", list(person.items()))
# Count pairs
print(f"Number of items: {len(person)}")
# Make a copy
person_copy = person.copy()
person_copy["name"] = "Bob"
print(f"Original name: {person['name']}")
print(f"Copy name: {person_copy['name']}")10. Nested Dictionaries
Dictionaries can contain other dictionaries (or lists) as values. This is useful for organizing complex data.
Try It: Nested Dictionaries
Dictionaries inside dictionaries
# Nested dictionary - users with details
users = {
"user1": {
"name": "Alice",
"age": 25,
"email": "alice@email.com"
},
"user2": {
"name": "Bob",
"age": 30,
"email": "bob@email.com"
}
}
# Access nested values
print("User1 name:", users["user1"]["name"])
print("User2 email:", users["user2"]["email"])
# Loop through nested dict
print("\nAll users:")
for user_id, info in users.items():
print(f" {user_id}: {info['name']} ({info['
...11. Dictionary Comprehension (Advanced)
Like list comprehension, you can create dictionaries in one line:
Try It: Dictionary Comprehension
Create dictionaries with one-line expressions
# Create a dictionary of squares
squares = {x: x**2 for x in range(1, 6)}
print("Squares:", squares)
# Create from two lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
people = {name: age for name, age in zip(names, ages)}
print("People:", people)
# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print("Even squares:", even_squares)12. Common Mistakes to Avoid
| Mistake | Problem | Solution |
|---|---|---|
| Accessing missing key | dict["missing"] | Use .get() or check with in |
| Using list as key | {[1,2]: "val"} | Keys must be immutable (str, int, tuple) |
| Using square brackets | ["key", "value"] | Use curly braces {"key": "value"} |
| Forgetting the colon | {"name" "Alice"} | Use {"name": "Alice"} |
| Duplicate keys | {"a": 1, "a": 2} | Each key must be unique (last value wins) |
13. Practical Examples
Example 1: User Profile
User Profile
Store and display user information
# Store user information
user = {
"username": "alice123",
"email": "alice@example.com",
"age": 25,
"is_verified": True
}
# Display profile
print("=== User Profile ===")
for key, value in user.items():
print(f"{key}: {value}")
# Update email
user["email"] = "alice.new@example.com"
print(f"\nUpdated email: {user['email']}")Example 2: Word Counter
Word Counter
Count occurrences of words
# Count word occurrences
text = "apple banana apple cherry banana apple"
words = text.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print("Word counts:")
for word, count in word_count.items():
print(f" {word}: {count}")Example 3: Simple Contact Book
Contact Book
Simple contact management
# Contact book
contacts = {
"Alice": "123-456-7890",
"Bob": "234-567-8901",
"Charlie": "345-678-9012"
}
# Look up a contact
name = "Bob"
if name in contacts:
print(f"{name}'s number: {contacts[name]}")
else:
print(f"{name} not found")
# Add new contact
contacts["Diana"] = "456-789-0123"
# List all contacts
print("\nAll contacts:")
for name, phone in contacts.items():
print(f" {name}: {phone}")Summary: Quick Reference
| Operation | Syntax | Example |
|---|---|---|
| Create | {key: value} | {"name": "Alice"} |
| Access (unsafe) | dict["key"] | person["name"] |
| Access (safe) | dict.get("key") | person.get("name") |
| Add/Change | dict["key"] = val | person["age"] = 25 |
| Remove | del dict["key"] | del person["age"] |
| Check exists | "key" in dict | "name" in person |
| Loop | for k, v in dict.items(): | for k, v in person.items(): |
| Length | len(dict) | len(person) |
Lesson 8 done — you can now model real-world data in Python!
Dictionaries are how Python stores structured data — user profiles, API responses, config settings. You know how to create, access, update, loop, and nest them safely.
🚀 Up next: File Handling — learn to save data permanently so it survives after your program closes.
Sign up for free to track which lessons you've completed and get learning reminders.