# Initialize Otter
import otter
grader = otter.Notebook("10_lab_dictionary_methods.ipynb")
# Validation: Check Python version and file location
import os
import sys
# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"
if current_version not in SUPPORTED_VERSIONS:
raise EnvironmentError(
f"Python version mismatch!\n"
f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
f"Found: {current_version}\n"
f"Please use Python 3.12 or 3.13 for this course."
)
print(f"Python version: {current_version}")
# Expected filename for this assignment
EXPECTED_FILE = "10_lab_dictionary_methods.ipynb"
# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lab_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)
if required_path_segment not in current_path and not in_allowed_env:
raise EnvironmentError(
f"File location error!\n"
f"This notebook should be in: ~/Documents/CSC115/lab_notebooks/\n"
f"Current location: {current_path}\n"
f"Please move this file to the correct directory."
)
# Verify filename (skip in grading/development environments)
if not in_allowed_env:
if not os.path.exists(EXPECTED_FILE):
notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
raise EnvironmentError(
f"Filename mismatch!\n"
f"Expected: {EXPECTED_FILE}\n"
f"Found notebooks: {notebooks}\n"
f"Please rename your notebook to '{EXPECTED_FILE}'."
)
print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
Hurricane Tracking Station¶
Goal: Work as a meteorologist analyzing storm track data from the National Hurricane Center. You will navigate nested data structures, build dictionary comprehensions, perform set operations on affected regions, and write your own functions with increasing independence.
This lab builds on Lecture 09's hurricane theme. You will work with time-series tracking data — latitude/longitude snapshots of each storm's path across the Atlantic, Gulf, and Caribbean.
What you will practice:
- Navigating nested dictionaries (dict of lists of dicts)
- Safe access with
.get() - Dictionary comprehension with filtering
- Iteration with
.items(),.keys(),.values() - Set creation and set operations (
&,-,|) - Writing functions with decreasing scaffolding
Storm Data¶
Run the cell below to load the hurricane tracking data and the map visualization helper. Do not edit this cell.
# --- STORM DATA AND VISUALIZATION (DO NOT EDIT) ---
# Run this cell to load the data. You will use storm_tracks and storm_regions throughout this lab.
import matplotlib.pyplot as plt
storm_tracks = {
"Milton": [
{"time": "2024-10-05 12:00", "lat": 21.1, "lon": -95.6, "wind_mph": 60, "category": 0},
{"time": "2024-10-06 12:00", "lat": 22.5, "lon": -93.2, "wind_mph": 85, "category": 1},
{"time": "2024-10-07 12:00", "lat": 24.8, "lon": -89.7, "wind_mph": 150, "category": 4},
{"time": "2024-10-08 06:00", "lat": 26.3, "lon": -86.1, "wind_mph": 165, "category": 5},
{"time": "2024-10-09 00:00", "lat": 27.6, "lon": -82.7, "wind_mph": 120, "category": 3},
],
"Helene": [
{"time": "2024-09-24 12:00", "lat": 19.5, "lon": -83.8, "wind_mph": 45, "category": 0},
{"time": "2024-09-25 12:00", "lat": 21.8, "lon": -84.5, "wind_mph": 80, "category": 1},
{"time": "2024-09-26 00:00", "lat": 24.2, "lon": -85.9, "wind_mph": 130, "category": 4},
{"time": "2024-09-26 18:00", "lat": 28.5, "lon": -84.3, "wind_mph": 140, "category": 4},
{"time": "2024-09-27 06:00", "lat": 32.1, "lon": -83.5, "wind_mph": 65, "category": 1},
],
"Ian": [
{"time": "2022-09-25 12:00", "lat": 15.3, "lon": -75.5, "wind_mph": 45, "category": 0},
{"time": "2022-09-26 12:00", "lat": 17.8, "lon": -78.2, "wind_mph": 105, "category": 2},
{"time": "2022-09-27 12:00", "lat": 20.5, "lon": -81.1, "wind_mph": 130, "category": 4},
{"time": "2022-09-28 06:00", "lat": 24.8, "lon": -82.5, "wind_mph": 155, "category": 4},
{"time": "2022-09-28 18:00", "lat": 26.6, "lon": -82.2, "wind_mph": 150, "category": 4},
],
"Idalia": [
{"time": "2023-08-28 12:00", "lat": 22.0, "lon": -84.5, "wind_mph": 50, "category": 0},
{"time": "2023-08-29 06:00", "lat": 25.5, "lon": -84.0, "wind_mph": 110, "category": 2},
{"time": "2023-08-30 00:00", "lat": 28.8, "lon": -83.4, "wind_mph": 130, "category": 3},
{"time": "2023-08-30 12:00", "lat": 31.2, "lon": -82.0, "wind_mph": 70, "category": 1},
],
"Nicole": [
{"time": "2022-11-08 12:00", "lat": 25.0, "lon": -70.5, "wind_mph": 50, "category": 0},
{"time": "2022-11-09 12:00", "lat": 26.5, "lon": -75.0, "wind_mph": 70, "category": 1},
{"time": "2022-11-10 06:00", "lat": 27.8, "lon": -79.5, "wind_mph": 75, "category": 1},
{"time": "2022-11-10 18:00", "lat": 28.5, "lon": -81.0, "wind_mph": 50, "category": 0},
],
"Irma": [
{"time": "2017-09-04 12:00", "lat": 17.4, "lon": -58.7, "wind_mph": 150, "category": 4},
{"time": "2017-09-05 12:00", "lat": 17.8, "lon": -62.0, "wind_mph": 185, "category": 5},
{"time": "2017-09-06 12:00", "lat": 18.3, "lon": -65.5, "wind_mph": 180, "category": 5},
{"time": "2017-09-08 12:00", "lat": 21.5, "lon": -74.5, "wind_mph": 160, "category": 5},
{"time": "2017-09-10 06:00", "lat": 25.1, "lon": -81.3, "wind_mph": 130, "category": 4},
{"time": "2017-09-10 18:00", "lat": 26.5, "lon": -81.6, "wind_mph": 110, "category": 2},
],
"Andrew": [
{"time": "1992-08-22 12:00", "lat": 25.0, "lon": -72.5, "wind_mph": 130, "category": 4},
{"time": "1992-08-23 06:00", "lat": 25.3, "lon": -76.0, "wind_mph": 155, "category": 5},
{"time": "1992-08-24 00:00", "lat": 25.5, "lon": -80.2, "wind_mph": 165, "category": 5},
{"time": "1992-08-24 12:00", "lat": 25.7, "lon": -83.5, "wind_mph": 140, "category": 4},
{"time": "1992-08-25 06:00", "lat": 27.0, "lon": -89.5, "wind_mph": 120, "category": 3},
],
}
storm_regions = {
"Milton": ["Tampa Bay", "Sarasota", "Orlando", "Fort Myers"],
"Helene": ["Tallahassee", "Atlanta", "Asheville"],
"Ian": ["Fort Myers", "Cape Coral", "Orlando", "Naples"],
"Idalia": ["Cedar Key", "Valdosta", "Tallahassee"],
"Nicole": ["Vero Beach", "Daytona Beach", "Orlando"],
"Irma": ["Key West", "Naples", "Fort Myers", "Miami", "Tampa Bay"],
"Andrew": ["Homestead", "Miami", "Florida City"],
}
def plot_storm_tracks(tracks, storm_names=None):
"""Plot hurricane tracks on a simple map. Students do not edit this function."""
colors = ["#e6194b", "#3cb44b", "#4363d8", "#f58231", "#911eb4", "#42d4f4", "#f032e6",
"#bfef45", "#fabed4", "#469990"]
fig, ax = plt.subplots(1, 1, figsize=(12, 8))
ax.set_facecolor("#d4e6f1")
# Simplified coastlines (polygon approximations)
# Florida
fl_lon = [-87.6, -85.5, -85.0, -84.0, -83.5, -82.5, -82.0, -81.5, -80.5, -80.1,
-80.1, -80.3, -81.0, -81.8, -82.0, -82.7, -83.0, -84.0, -85.5, -86.5,
-87.4, -87.6]
fl_lat = [30.9, 30.3, 29.8, 29.9, 29.3, 29.1, 28.5, 27.5, 26.5, 25.8,
25.2, 25.0, 24.5, 24.5, 24.9, 25.5, 26.5, 27.8, 29.5, 30.3,
30.5, 30.9]
ax.fill(fl_lon, fl_lat, color="#c8c8c8", edgecolor="#888888", linewidth=0.8, zorder=2)
# Cuba
cuba_lon = [-84.9, -83.5, -82.0, -80.0, -78.0, -76.0, -74.2, -74.5, -76.0, -78.0,
-80.0, -82.0, -83.5, -84.9]
cuba_lat = [21.8, 22.5, 23.1, 23.0, 22.4, 21.8, 20.2, 19.8, 19.9, 20.5,
21.5, 22.0, 22.2, 21.8]
ax.fill(cuba_lon, cuba_lat, color="#c8c8c8", edgecolor="#888888", linewidth=0.8, zorder=2)
# Gulf Coast (TX to AL)
gulf_lon = [-97.5, -96.0, -94.5, -93.5, -92.0, -90.5, -89.5, -89.0, -88.5, -87.6]
gulf_lat = [26.0, 28.5, 29.5, 29.8, 29.2, 29.3, 29.5, 30.2, 30.5, 30.9]
ax.plot(gulf_lon, gulf_lat, color="#888888", linewidth=1.5, zorder=2)
ax.fill_between(gulf_lon, gulf_lat, [32] * len(gulf_lon), color="#c8c8c8", zorder=2)
# Determine which storms to plot
names = storm_names if storm_names else list(tracks.keys())
for i, name in enumerate(names):
if name not in tracks:
continue
points = tracks[name]
lats = [p["lat"] for p in points]
lons = [p["lon"] for p in points]
winds = [p["wind_mph"] for p in points]
color = colors[i % len(colors)]
# Track line
ax.plot(lons, lats, color=color, linewidth=2, alpha=0.7, zorder=3)
# Markers scaled by wind speed
for lon, lat, wind in zip(lons, lats, winds):
size = max(15, wind / 3)
ax.scatter(lon, lat, s=size, color=color, edgecolors="black",
linewidths=0.5, zorder=4)
# Start marker (square) and end marker (triangle)
ax.scatter(lons[0], lats[0], s=80, color=color, marker="s",
edgecolors="black", linewidths=1, zorder=5)
ax.scatter(lons[-1], lats[-1], s=80, color=color, marker="^",
edgecolors="black", linewidths=1, zorder=5)
# Label at start
ax.annotate(name, (lons[0], lats[0]), textcoords="offset points",
xytext=(8, 8), fontsize=9, fontweight="bold", color=color, zorder=6)
ax.set_xlim(-100, -55)
ax.set_ylim(14, 34)
ax.set_xlabel("Longitude", fontsize=12)
ax.set_ylabel("Latitude", fontsize=12)
ax.set_title("Hurricane Tracking Station", fontsize=16, fontweight="bold")
ax.grid(True, alpha=0.3)
ax.set_aspect("equal")
plt.tight_layout()
plt.show()
print("Storm data loaded! 7 storms with tracking points and regional impact data.")
print(f"Storms: {', '.join(storm_tracks.keys())}")
Visualize the Data¶
Run the cell below to see all 7 hurricane tracks plotted on a map. Squares mark where each storm started tracking, triangles mark the end, and larger dots mean higher wind speeds.
# Plot all storm tracks on the map
plot_storm_tracks(storm_tracks)
Part A: Building the Tracker¶
Quick Recap: Navigating Nested Structures¶
Our storm_tracks dictionary is a dict of lists of dicts — a common pattern for time-series data. Here is how to access data at each level:
# Level 1: Get a storm's list of tracking points
storm_tracks["Milton"] # returns a list of dicts
# Level 2: Get a specific tracking point (by index)
storm_tracks["Milton"][0] # returns the first tracking point dict
# Level 3: Get a specific field from a tracking point
storm_tracks["Milton"][0]["lat"] # returns 21.1
# Safe access: use .get() to avoid KeyError on missing storms
storm_tracks.get("Katrina", []) # returns [] instead of crashing
Run the demo cell below to see these in action.
# DEMO: Navigating nested structures
# Access the latitude of Helene's third tracking point
helene_third_lat = storm_tracks["Helene"][2]["lat"]
print(f"Helene's 3rd tracking point latitude: {helene_third_lat}")
# Count how many tracking points Ian has using len()
ian_point_count = len(storm_tracks["Ian"])
print(f"Ian has {ian_point_count} tracking points")
# Safe access for a storm that does not exist
unknown = storm_tracks.get("Katrina", [])
print(f"Katrina tracking points: {unknown} (empty list = not found)")
Question 1: Find Milton's Peak¶
Look through Milton's tracking points and find:
- The highest wind speed recorded across all tracking points
- The time when that peak wind speed occurred
- The total number of tracking points Milton has
Set the three variables below.
# ✏️ YOUR ANSWER HERE
milton_peak_wind = ...
milton_peak_time = ...
...
...
milton_peak_wind = ...
milton_peak_time = ...
milton_total_points = ...
grader.check("q1_milton_peak")
Question 2: Storm Peak Lookup Function¶
Write a function that looks up the peak wind speed and category for any storm. If the storm does not exist in the data, return a default result instead of crashing.
# ✏️ YOUR ANSWER HERE
def get_storm_peak(storm_tracks, storm_name):
"""Look up the peak wind speed and category for a storm.
Parameters:
storm_tracks: a dictionary mapping storm names to lists of tracking point dicts
storm_name: a string, the name of the storm to look up
Returns:
A dictionary with keys "name", "peak_wind", and "peak_category".
If the storm exists, peak_wind and peak_category are the maximum values
from the tracking points.
If the storm does NOT exist, return {"name": storm_name, "peak_wind": 0, "peak_category": 0}
"""
points = ...
...
...
peak_wind = ...
peak_cat = ...
...
...
...
...
grader.check("q2_get_storm_peak")
Question 3: Add a New Storm¶
A new storm needs to be added to the tracking system. Raw data arrives as a list of tuples. Write a function that converts the raw data into the proper tracking point format and adds it to a copy of the tracking dictionary.
# This is the raw data for Hurricane Dorian. Run this cell before answering Q3.
dorian_data = [
("2019-09-01 12:00", 26.5, -76.5, 185, 5),
("2019-09-02 12:00", 26.6, -77.8, 180, 5),
("2019-09-03 12:00", 27.5, -78.5, 120, 3),
]
# ✏️ YOUR ANSWER HERE
def add_storm(storm_tracks, storm_name, raw_data):
"""Add a new storm to the tracking system.
Parameters:
storm_tracks: the existing storm tracking dictionary
storm_name: a string, the name of the new storm
raw_data: a list of tuples, each containing (time, lat, lon, wind_mph, category)
Returns:
A NEW dictionary (copy of storm_tracks) with the new storm added.
Each tuple in raw_data should become a dict with keys:
"time", "lat", "lon", "wind_mph", "category"
The original storm_tracks must NOT be modified.
"""
updated = ...
tracking_points = ...
...
...
updated[storm_name] = ...
...
# Call your function to create updated_tracks
updated_tracks = ...
grader.check("q3_add_storm")
Visualize: See Dorian on the Map¶
Now that you have added Dorian to the tracking system, run the cell below to see it on the map alongside the other storms.
# Plot updated tracks including Dorian
plot_storm_tracks(updated_tracks)
Part B: Analysis¶
Quick Recap: Dictionary Comprehension and Iteration¶
Dictionary comprehension lets you build a new dictionary in a single expression:
# Syntax: {key_expr: value_expr for variable in iterable}
# With filter: {key_expr: value_expr for variable in iterable if condition}
# .items() gives you both key and value when iterating:
for name, points in storm_tracks.items():
print(name, len(points))
Run the demo cell below to see a comprehension example.
# DEMO: Dictionary comprehension — count tracking points per storm
# This maps each storm name to how many tracking points it has.
point_counts = {name: len(points) for name, points in storm_tracks.items()}
print("Tracking points per storm:")
for name, count in point_counts.items():
print(f" {name}: {count} points")
Question 4: Peak Winds Comprehension¶
Use a dictionary comprehension to create a dictionary that maps each storm name to its highest recorded wind speed. You will need to use max() to find the highest value in each storm's list of tracking points.
Hint: max(list, key=...) can find the maximum item based on a specific field.
# ✏️ YOUR ANSWER HERE
peak_winds = ...
grader.check("q4_peak_winds")
Question 5: Filter Major Hurricanes¶
Write a function that returns only the storms that reached major hurricane strength (category 3 or higher) at any point during their track. The returned dictionary should have the same structure as storm_tracks — storm names mapping to their full list of tracking points.
# ✏️ YOUR ANSWER HERE
def get_major_hurricanes(storm_tracks):
# storm_tracks: the storm tracking dictionary
# Return a dictionary with only storms that reached category 3 or higher
...
major_hurricanes = ...
grader.check("q5_major_hurricanes")
Visualize: Major Hurricanes Only¶
Try plotting only the major hurricanes to see how the most powerful storms compare on the map.
# Plot only the major hurricanes
plot_storm_tracks(storm_tracks, list(major_hurricanes.keys()))
Question 6: Storm Summary Report¶
Write a function that creates a summary report of all storms. Each storm should be described in a single formatted string, and the list should be sorted from strongest to weakest by peak wind speed.
Each string should follow this exact format:
Irma: 6 points, peak 185 mph (Cat 5)
# ✏️ YOUR ANSWER HERE
def storm_summary(storm_tracks):
# storm_tracks: the storm tracking dictionary
summaries = ...
...
num_points = ...
peak_wind = ...
peak_cat = ...
...
...
...
summary_report = ...
grader.check("q6_storm_summary")
Part C: Multi-Storm Comparison¶
Quick Recap: Sets and Set Operations¶
A set is an unordered collection of unique items. You can create a set from a list to remove duplicates, and then use set operations to compare groups.
# Create sets from lists
set_a = set(["apple", "banana", "cherry"])
set_b = set(["banana", "date", "cherry"])
# Intersection: items in BOTH sets
set_a & set_b # {"banana", "cherry"}
# Difference: items in A but NOT in B
set_a - set_b # {"apple"}
# Union: items in EITHER set (or both)
set_a | set_b # {"apple", "banana", "cherry", "date"}
Run the demo cell below to see set operations on a simple example.
# DEMO: Set operations with tropical weather zones
atlantic_storms = {"Arlene", "Bret", "Cindy", "Don"}
gulf_storms = {"Bret", "Don", "Emily", "Franklin"}
print("Atlantic storms:", atlantic_storms)
print("Gulf storms:", gulf_storms)
print()
print("In BOTH zones:", atlantic_storms & gulf_storms)
print("Atlantic only:", atlantic_storms - gulf_storms)
print("ALL storms:", atlantic_storms | gulf_storms)
Question 7: Regional Impact Analysis¶
Using storm_regions, compute the following sets. Remember that storm_regions maps storm names to lists of city names — you will need to convert those lists to sets.
# ✏️ YOUR ANSWER HERE
# Cities hit by BOTH Milton and Ian
milton_ian_shared = ...
# Cities hit by Irma but NOT by Andrew
irma_not_andrew = ...
# ALL unique cities affected by ANY storm
all_affected_cities = ...
...
# Set of storm names that affected any city in south_florida
south_florida = {"Miami", "Fort Myers", "Key West", "Homestead", "Naples"}
south_florida_storms = ...
grader.check("q7_set_operations")
Question 8: Build a City Impact Report¶
Write a function called city_impact_report that takes two parameters:
- A storm regions dictionary (like
storm_regions) - A list of city names to investigate
The function should return a dictionary where each city maps to a set of storm names that affected it. Only include cities that were actually affected by at least one storm — skip any cities with no matching storms.
For example, city_impact_report(storm_regions, ["Orlando", "Miami", "Atlantis"]) should return:
{
"Orlando": {"Milton", "Ian", "Nicole"},
"Miami": {"Irma", "Andrew"},
}
Notice that "Atlantis" is not in the result because no storms affected it.
You write the entire function yourself — define the name, parameters, docstring, and logic.
# ✏️ YOUR ANSWER HERE
...
report = ...
...
storms_hitting = ...
...
...
grader.check("q8_city_impact_report")
What You Just Did (in Python!)¶
| What You Did | Python Concept |
|---|---|
Navigated storm_tracks["Milton"][0]["wind_mph"] |
Nested dict/list access |
Used .get() for safe lookups |
Avoiding KeyError |
| Built tracking point dicts from tuples | Dict construction |
Created peak_winds with {k: v for ...} |
Dictionary comprehension |
| Filtered storms by category | Dict comprehension with if |
| Sorted summaries by wind speed | .items() iteration, sorted() with key |
Found milton_ian_shared with & |
Set intersection |
Found irma_not_andrew with - |
Set difference |
Combined all cities with .update() |
Set union |
Wrote city_impact_report from scratch |
Function design |
Submitting to Gradescope¶
This file is saved on your computer — you do not need to download it from Jupyter.
Find the file on your computer:
- Mac: Open Finder →
Documents/CSC115/lab_notebooks/10_lab_dictionary_methods/10_lab_dictionary_methods.ipynb - Windows: Open File Explorer →
Documents\CSC115\lab_notebooks\10_lab_dictionary_methods\10_lab_dictionary_methods.ipynb
- Mac: Open Finder →
Upload to Gradescope:
- Go to gradescope.com and open this assignment
- Click "Submit" and upload the
.ipynbfile - The filename must be exactly
10_lab_dictionary_methods.ipynb
Do NOT use File > Download in Jupyter — this can rename the file and cause submission errors.
You have completed the Hurricane Tracking Station lab.
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()