Python course ยท Module 2: Data Structures
Dictionaries - Cataloging Discoveries
In this lesson17
Welcome back! Darwin here with another important lesson.
In the previous lesson you learned about lists - ordered collections like expedition trails. But sometimes you need something more - a way to catalog your discoveries with additional information. In the jungle every species has its data card: habitat, size, whether it's dangerous. In Python we use dictionaries for this.
What Are Dictionaries?
A dictionary is a collection of key: value pairs. Imagine a catalog of discoveries where each species (key) has its information card (value).
# Species catalog - key is the name, value is the details
species_info = {
"Python regius": "Royal python, 1-2m, harmless",
"Panthera leo": "Lion, 2-3m, very dangerous",
"Loxodonta africana": "African elephant, 3-4m, calm"
}
# More complex catalog
detailed_catalog = {
"Python regius": {
"common_name": "Royal Python",
"length_m": 1.5,
"habitat": "jungle",
"dangerous": False
},
"Panthera leo": {
"common_name": "Lion",
"length_m": 2.5,
"habitat": "savanna",
"dangerous": True
}
}Key characteristics of dictionaries:
- Key-value pairs - each key leads to a value
- Keep insertion order (since Python 3.7), but have no indices - you get a value by its key
- Keys must be unique and immutable (string, int, tuple)
- Values can be anything - even other dictionaries!
- Mutable - they can be modified
Creating Dictionaries
# Empty dictionary - clean catalog
empty_catalog = {}
empty_dict = dict()
# Dictionary with data
explorer_data = {
"name": "Darwin",
"age": 35,
"profession": "Researcher",
"discoveries": 47
}
# Different key types (but strings are most common)
mixed_keys = {
"name": "Python",
42: "Answer",
(10, 20): "Coordinates"
}
# Nested dictionaries
expedition = {
"location": "Amazonia",
"team": {
"leader": "Darwin",
"count": 5
},
"equipment": ["Binoculars", "Map", "GPS"]
}
# dict() constructor
from_pairs = dict([("A", 1), ("B", 2), ("C", 3)])
with_kwargs = dict(name="Darwin", age=35, job="Explorer")Accessing Values
species = {
"Python regius": "Royal Python",
"Panthera leo": "Lion",
"Loxodonta africana": "Elephant"
}
# Access by key (square brackets)
python_name = species["Python regius"] # "Royal Python"
lion_name = species["Panthera leo"] # "Lion"
# KeyError if key doesn't exist!
# wrong = species["Tyrannosaurus"] # KeyError!
# Safe access - get()
python_name = species.get("Python regius") # "Royal Python"
trex = species.get("Tyrannosaurus") # None
trex = species.get("Tyrannosaurus", "Not found") # "Not found"
print(f"Python: {python_name}")get() vs []:
dict[key]- raises KeyError if key is missingdict.get(key)- returns None if key is missingdict.get(key, default)- returns default if key is missing
Adding and Modifying
catalog = {
"Python regius": {"length": 1.5, "habitat": "jungle"}
}
# Adding a new entry
catalog["Panthera leo"] = {"length": 2.5, "habitat": "savanna"}
# Modifying an existing one
catalog["Python regius"]["length"] = 1.8
# Adding via update() - dictionary or key-value pairs
catalog.update({"Loxodonta africana": {"length": 4.0, "habitat": "savanna"}})
catalog.update(discovered_by="Darwin", year=2024)
print(catalog)Removing Elements
species = {
"Python": "Python",
"Leo": "Lion",
"Elephas": "Elephant",
"Giraffa": "Giraffe"
}
# del - remove by key
del species["Giraffa"]
# pop() - remove and return value
leo_value = species.pop("Leo") # "Lion"
print(leo_value)
# pop() with default (if key doesn't exist)
dino = species.pop("T-Rex", "Not found") # "Not found"
# popitem() - remove and return the LAST pair (Python 3.7+)
last_item = species.popitem() # ("Elephas", "Elephant")
# clear() - clear the entire dictionary
species.clear()
print(species) # {}Checking Key Existence
catalog = {
"Python regius": "Python",
"Panthera leo": "Lion"
}
# in - check if key exists
if "Python regius" in catalog:
print("Python is in the catalog!")
if "T-Rex" not in catalog:
print("T-Rex is not in the catalog")
# Note: 'in' checks KEYS, not values!
print("Python" in catalog) # False (that's a value, not a key!)Iterating Through a Dictionary
species = {
"Python regius": "Royal Python",
"Panthera leo": "Lion",
"Loxodonta africana": "African Elephant"
}
# Iterating through keys (default)
for species_name in species:
print(species_name)
# Explicitly through keys - keys()
for key in species.keys():
print(key)
# Iterating through values - values()
for common_name in species.values():
print(common_name)
# Iterating through key-value pairs - items() (most common!)
for species_name, common_name in species.items():
print(f"{species_name}: {common_name}")
# Enumerate for numbering
for i, (key, value) in enumerate(species.items(), start=1):
print(f"{i}. {key} -> {value}")Dictionary Methods
keys(), values(), items()
catalog = {
"Python": {"habitat": "jungle", "size": 1.5},
"Leo": {"habitat": "savanna", "size": 2.5}
}
# All keys
all_keys = catalog.keys() # dict_keys(['Python', 'Leo'])
keys_list = list(catalog.keys()) # List: ['Python', 'Leo']
# All values
all_values = catalog.values() # dict_values([{...}, {...}])
# All pairs
all_items = catalog.items() # dict_items([('Python', {...}), ('Leo', {...})])
# Conversion to lists
keys = list(catalog.keys())
values = list(catalog.values())
items = list(catalog.items())get() - safe access
species = {"Python": "Python", "Leo": "Lion"}
# get(key) - None if missing
result = species.get("Python") # "Python"
result = species.get("T-Rex") # None
# get(key, default) - custom default
result = species.get("T-Rex", "Not found!") # "Not found!"setdefault() - return value OR set a default
catalog = {"Python": {"count": 5}}
# If key exists - return value
python_data = catalog.setdefault("Python", {"count": 0})
print(python_data) # {'count': 5}
# If key does NOT exist - add with default
leo_data = catalog.setdefault("Leo", {"count": 0})
print(leo_data) # {'count': 0}
print(catalog) # {'Python': {...}, 'Leo': {'count': 0}}update() - update/merge dictionaries
catalog1 = {"Python": "Python", "Leo": "Lion"}
catalog2 = {"Elephas": "Elephant", "Giraffa": "Giraffe"}
new_data = {"Python": "Royal Python"} # Will overwrite
# Update with dictionary
catalog1.update(catalog2)
print(catalog1) # {'Python': 'Python', 'Leo': 'Lion', 'Elephas': 'Elephant', 'Giraffa': 'Giraffe'}
# Update with key=value pairs
catalog1.update(discovered_by="Darwin", year=2024)copy() - copying a dictionary
# WARNING - this does NOT copy!
original = {"A": 1, "B": 2}
reference = original # Same reference!
reference["A"] = 999
print(original) # {'A': 999, 'B': 2} - changed!
# Proper copying
original = {"A": 1, "B": 2}
copy1 = original.copy() # Shallow copy
copy2 = dict(original) # Alternative
copy1["A"] = 999
print(original) # {'A': 1, 'B': 2} - unchanged!
# Deep copy (for nested dictionaries)
import copy
nested = {"team": {"leader": "Darwin", "size": 5}}
deep = copy.deepcopy(nested)
deep["team"]["leader"] = "Alex"
print(nested) # {'team': {'leader': 'Darwin', 'size': 5}} - unchanged!Dictionary Comprehensions
Similar to list comprehensions, you can create dictionaries in a single line!
# Traditional way
squares = {}
for x in range(1, 6):
squares[x] = x ** 2
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Dict comprehension!
squares = {x: x ** 2 for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With condition
even_squares = {x: x ** 2 for x in range(1, 11) if x % 2 == 0}
# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
# Swapping keys and values
species = {"Python": "Python", "Leo": "Lion"}
reversed_dict = {value: key for key, value in species.items()}
# {"Python": "Python", "Lion": "Leo"}
# From two lists
names = ["Python", "Leo", "Elephas"]
common_names = ["Python", "Lion", "Elephant"]
catalog = {name: common for name, common in zip(names, common_names)}Nested Dictionaries
Dictionaries can contain other dictionaries - perfect for complex data!
# Expedition catalog with details for each species
species_database = {
"Python regius": {
"common_name": "Royal Python",
"characteristics": {
"length_m": 1.5,
"weight_kg": 2.5,
"habitat": "jungle"
},
"status": "discovered",
"discoverer": "Darwin",
"date": "2024-01-15"
},
"Panthera leo": {
"common_name": "Lion",
"characteristics": {
"length_m": 2.5,
"weight_kg": 190,
"habitat": "savanna"
},
"status": "observed",
"discoverer": "Team B"
}
}
# Accessing nested values
python_length = species_database["Python regius"]["characteristics"]["length_m"]
print(f"Python length: {python_length}m")
# Safe access to deeply nested values
leo_weight = species_database.get("Panthera leo", {}).get("characteristics", {}).get("weight_kg", "No data")
print(f"Lion weight: {leo_weight}kg")Operations on Dictionaries
# Length (number of key-value pairs)
species = {"Python": "Python", "Leo": "Lion", "Elephas": "Elephant"}
count = len(species) # 3
# Merging dictionaries (Python 3.9+)
dict1 = {"A": 1, "B": 2}
dict2 = {"C": 3, "D": 4}
merged = dict1 | dict2 # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
# Merging with overwriting (Python 3.9+)
dict1 = {"A": 1, "B": 2}
dict2 = {"B": 999, "C": 3}
merged = dict1 | dict2 # {'A': 1, 'B': 999, 'C': 3} - B overwritten!
# |= operator (modifies the first dictionary)
dict1 |= dict2 # dict1 now contains merged data
# Min/Max of keys
species = {"Python": 5, "Leo": 12, "Elephas": 3}
max_key = max(species) # "Python" (alphabetically)
max_value = max(species.values()) # 12
max_by_value = max(species, key=species.get) # "Leo" (highest value)Sorting Dictionaries
species_count = {
"Python": 5,
"Leo": 12,
"Elephas": 3,
"Giraffa": 8
}
# Sort by keys
sorted_by_key = dict(sorted(species_count.items()))
# {'Elephas': 3, 'Giraffa': 8, 'Leo': 12, 'Python': 5}
# Sort by values
sorted_by_value = dict(sorted(species_count.items(), key=lambda x: x[1]))
# {'Elephas': 3, 'Python': 5, 'Giraffa': 8, 'Leo': 12}
# Sort descending by values
sorted_desc = dict(sorted(species_count.items(), key=lambda x: x[1], reverse=True))
# {'Leo': 12, 'Giraffa': 8, 'Python': 5, 'Elephas': 3}Practical Example - Cataloging System
# System for cataloging discovered species
species_catalog = {}
def add_species(name, common_name, habitat, dangerous, notes=""):
"""Add a species to the catalog"""
species_catalog[name] = {
"common_name": common_name,
"habitat": habitat,
"dangerous": dangerous,
"notes": notes,
"discovery_date": "2024-11-24" # Example date
}
print(f"Added: {name}")
def show_catalog():
"""Display the entire catalog"""
if not species_catalog:
print("Catalog is empty!")
return
print(f"\n=== SPECIES CATALOG ({len(species_catalog)} entries) ===")
for name, data in species_catalog.items():
danger = "DANGEROUS" if data["dangerous"] else "Safe"
print(f"\n{name} ({data['common_name']})")
print(f" Habitat: {data['habitat']}")
print(f" Status: {danger}")
if data["notes"]:
print(f" Notes: {data['notes']}")
def search_species(name):
"""Search for a species by name"""
if name in species_catalog:
data = species_catalog[name]
print(f"\nFound: {name}")
print(f"Common name: {data['common_name']}")
print(f"Habitat: {data['habitat']}")
print(f"Dangerous: {'Yes' if data['dangerous'] else 'No'}")
else:
print(f"\nNot found: {name}")
def filter_by_habitat(habitat):
"""Filter species by habitat"""
filtered = {name: data for name, data in species_catalog.items()
if data["habitat"] == habitat}
print(f"\nSpecies in habitat '{habitat}': {len(filtered)}")
for name in filtered:
print(f" - {name}")
# Using the system
add_species("Python regius", "Royal Python", "jungle", False, "Calm species")
add_species("Panthera leo", "Lion", "savanna", True, "Observe from a distance!")
add_species("Gorilla gorilla", "Gorilla", "jungle", False)
show_catalog()
search_species("Python regius")
filter_by_habitat("jungle")List vs Dictionary - When to Use Which?
Use a list when:
- Order is important
- You need access by numeric index
- You can have duplicates
- Simple collection of values
Use a dictionary when:
- You need fast access by key
- Each element has its own unique label
- Data has a key-value structure
- You want to easily check if an element exists
Practical Exercise
The editor holds the expedition register safari_registry. Complete it:
- Add the key
"vehicle"with the value"jeep" - Change
"budget_usd"to 20000 - Use
update()to add"species_found": 12and"photos_taken": 340 - Remove the key
"days_remaining"withdel
Code for this lesson: main.py
# Adding and updating dictionary entries
safari_registry = {
"expedition_name": "Serengeti 2024",
"leader": "Darwin",
"team_size": 5
}
print("Initial registry:")
print(safari_registry)
# Adding a new key
safari_registry["location"] = "Tanzania"
safari_registry["budget_usd"] = 15000
# Updating an existing key
safari_registry["team_size"] = 7
print("\nAfter changes:")
print(safari_registry)
# update() - updates multiple keys at once
safari_registry.update({
"status": "active",
"days_remaining": 14,
"leader": "Jane" # Overwrites existing
})
print("\nAfter update():")
print(safari_registry)
# TODO: Add key "vehicle" with value "jeep"
# TODO: Change "budget_usd" to 20000
# TODO: Use update() to add "species_found": 12 and "photos_taken": 340
# TODO: Remove the key "days_remaining" using del
# del safari_registry["?"]
print("\nFinal registry:")
for key, value in safari_registry.items():
print(f" {key}: {value}")
Summary
In this lesson you learned:
- What dictionaries are (key-value pairs)
- Creating and accessing dictionaries
- Adding, modifying, removing elements
- Methods: keys(), values(), items(), get(), update(), setdefault()
- Dictionary comprehensions
- Nested dictionaries
- Iterating through dictionaries
- Sorting and operations on dictionaries
Checkpoint
Before moving on:
- You understand the difference between a list and a dictionary
- You can use get() instead of []
- You know items(), keys(), values()
- You can iterate through a dictionary
- You can create dict comprehensions
- You understand nested dictionaries
In the next lesson Darwin will show you tuples and sets - permanent records and a register of unique species!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. A dictionary in Python stores:
2. How do you get the value of the key 'name' from the dictionary 'animal'?
3. What is the advantage of dict.get('key') over dict['key']?
4. What does dict.items() return?
Hands-on tasks in the game
- Click in order
Click the elements in the correct order:
- Code editor
Create a dictionary called 'tiger' with keys: name='Tiger', weight=200, dangerous=True
- Code editor
Print the name of the animal from the dictionary animal = {'name': 'Python', 'length': 5}
- Code editor
Add the key 'habitat' with the value 'Jungle' to the dictionary animal = {'name': 'Python', 'length': 5}
- Vertical ordering
Arrange the steps for building a catalog:
- Horizontal ordering
Arrange: animal = {'name': 'Tiger'}
- Click in order
Click in order: print(animal['name'])
- Vertical ordering
Arrange: create a dictionary, add a key, print all keys:
Tasks after this lesson
- QuestionWhat is a Dictionary?
- QuestionAccessing a Value
- QuestionThe get() Method
- Click in orderBuilding a List Comprehension
- QuestionIterating Over a Dictionary
- Coding taskCreating a Dictionary
- Coding taskAccessing Data
- Coding taskAdding to a Dictionary
- Put in orderWorking with a Dictionary - Full Cycle
- Put in orderCreating a Dictionary
- Click in orderAccessing a Value
- Put in orderWorking with a Dictionary