In [ ]:
# Initialize Otter
import otter
grader = otter.Notebook("09_lecture_dictionaries_and_sets.ipynb")

Lecture 09: Dictionaries and Sets

Theme: Hurricane Season Tracker — Tracking Atlantic hurricane data for South Florida

Goal: Learn to use dictionaries (key-value data), sets (unique collections), and JSON serialization. By the end of this notebook, you will be able to:

  • Create dictionaries and access values by key
  • Add, update, and delete dictionary entries
  • Use .get() for safe key lookup
  • Build nested dictionaries for structured data
  • Iterate over dictionaries with .items(), .keys(), .values()
  • Use dictionary comprehensions to filter and transform
  • Create sets and perform set operations (union, intersection, difference)
  • Save and load data with the json module

Important: Run cells in order from top to bottom. Later questions use variables from earlier cells.

In [ ]:
# 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 = "09_lecture_dictionaries_and_sets.ipynb"

# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_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/lecture_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)}")

1. What is a Dictionary?

A dictionary maps keys to values — like a real dictionary maps words to definitions.

  • A list stores items by position (index 0, 1, 2...)
  • A dictionary stores items by name (any key you choose)

Dictionaries use curly braces {} and colons : to separate keys from values.

In [ ]:
# Reading the dict syntax
#
# example_dict = {"Milton": 5, "Helene": 4}
#                  ^        ^
#                  |        |__ value (the data)
#                  |__ key (the lookup name)
#
#  { key: value, key: value }
#    ^  ^  ^
#    |  |  |__ each pair separated by commas
#    |  |__ colon separates key from value
#    |__ curly braces wrap the whole dict

# Creating an empty dict
empty_tracker = {}
print(f"Empty dict: {empty_tracker}")
print(f"Type: {type(empty_tracker)}")

# Creating a dict with data
demo_scores = {"Algebra": 92, "Biology": 88, "Chemistry": 75}
print(f"\nDemo scores: {demo_scores}")
print(f"Number of entries: {len(demo_scores)}")

# Keys must be unique — duplicates overwrite silently!
demo_duplicates = {"A": 1, "B": 2, "A": 99}
print(f"\nDuplicate key 'A': {demo_duplicates}")  # {'A': 99, 'B': 2}

Question 1: Create a Storm Category Dictionary (1 point)

Create a dictionary called storm_categories that maps hurricane names to their Saffir-Simpson category numbers. Include these five storms:

Storm Category
Milton 5
Helene 4
Ian 4
Idalia 3
Nicole 1
In [ ]:
# YOUR CODE HERE
storm_categories = ...

print(f"Storm categories: {storm_categories}")
print(f"Number of storms tracked: {len(storm_categories)}")
In [ ]:
grader.check("q1_create_dict")

2. Adding and Updating Entries

To add a new entry or update an existing one, use the same syntax:

dict[key] = value
  • If the key doesn't exist yet, it adds a new entry.
  • If the key already exists, it overwrites the old value.

Same syntax, two different effects — pay attention to whether the key is new or existing.

In [ ]:
# Adding and updating use the SAME syntax: dict[key] = value

demo_tracker = {"Milton": 5, "Helene": 4}
print(f"Before: {demo_tracker}")

# ADD a new storm (key doesn't exist yet)
demo_tracker["Debby"] = 1
print(f"After adding Debby: {demo_tracker}")

# UPDATE an existing storm (key already exists — overwrites!)
# "The NHC re-analyzed Milton and downgraded it to category 4"
demo_tracker["Milton"] = 4
print(f"After updating Milton: {demo_tracker}")

# The syntax is identical — Python checks if the key exists
# New key → add, existing key → overwrite

Question 2: Update the Tracker (1 point)

Start by making a copy of storm_categories called updated_categories (use .copy()).

Then update the tracker:

  1. A new storm has been identified: store its name "Debby" in new_storm_name and its category 1 in new_storm_category. Add it to updated_categories.
  2. The NHC re-analyzed Milton and downgraded it. Update Milton's category to 4 in updated_categories.
In [ ]:
# YOUR CODE HERE
updated_categories = ...
new_storm_name = ...
new_storm_category = ...
updated_categories[new_storm_name] = ...
updated_categories["Milton"] = ...

print(f"Updated tracker: {updated_categories}")
print(f"Added: {new_storm_name} (category {new_storm_category})")
print(f"Milton is now category {updated_categories['Milton']}")
In [ ]:
grader.check("q2_add_update")

3. Retrieving Values

Two ways to get a value from a dictionary:

  1. dict[key] — direct lookup. Crashes with KeyError if the key doesn't exist.
  2. dict.get(key, default) — safe lookup. Returns the default value if the key doesn't exist.
In [ ]:
# Two ways to retrieve a value from a dict
#
# storm_categories["Milton"]          → 5 (works!)
# storm_categories["Katrina"]         → KeyError! Crashes!
#
# storm_categories.get("Milton", 0)   → 5 (works!)
# storm_categories.get("Katrina", 0)  → 0 (safe — returns the default)
#                       ^          ^
#                       |          |__ default value if key not found
#                       |__ key to look up

# Direct lookup — works when key exists
print(f"Milton's category: {storm_categories['Milton']}")

# .get() with default — safe when key might not exist
result = storm_categories.get("Katrina", 0)
print(f"Katrina's category: {result}")  # 0 (not in our tracker)

# .get() without a default returns None
result_none = storm_categories.get("Katrina")
print(f"Without default: {result_none}")  # None

Question 3: Safe Storm Lookup (1 point)

Look up Milton's category from storm_categories using direct access (dict[key]) and store it in milton_category.

Then look up "Katrina" — but Katrina isn't in our tracker. Use the safe retrieval method to get a default of 0 instead of crashing, and store the result in katrina_category.

Finally, look up "Andrew" the same safe way with a default of 0 and store it in unknown_storm_result.

In [ ]:
# YOUR CODE HERE
milton_category = ...
katrina_category = ...
unknown_storm_result = ...

print(f"Milton: category {milton_category}")
print(f"Katrina: category {katrina_category}")
print(f"Andrew: category {unknown_storm_result}")
In [ ]:
grader.check("q3_retrieval")

4. Checking Membership and Deleting Entries

Just like with lists, use in and not in to check if a key exists. For dicts, in checks keys, not values.

Use del dict[key] to remove an entry entirely.

In [ ]:
# in / not in checks KEYS (not values!)
print(f"Is Milton tracked? {'Milton' in storm_categories}")
print(f"Is Katrina tracked? {'Katrina' in storm_categories}")
print(f"Is Katrina NOT tracked? {'Katrina' not in storm_categories}")

# del removes a key-value pair entirely
demo_del = storm_categories.copy()
print(f"\nBefore del: {demo_del}")
del demo_del["Nicole"]
print(f"After del Nicole: {demo_del}")
print(f"Count: {len(demo_del)}")

Question 4: Track and Remove Storms (1 point)

Using storm_categories:

  1. Check if "Milton" is being tracked and store the result (a boolean) in is_milton_tracked.
  2. Check if "Katrina" is being tracked and store the result in is_katrina_tracked.
  3. Create a copy of storm_categories called remaining_storms, then remove the weakest storm (Nicole) from the copy.
In [ ]:
# YOUR CODE HERE
is_milton_tracked = ...
is_katrina_tracked = ...
remaining_storms = ...
...

print(f"Milton tracked? {is_milton_tracked}")
print(f"Katrina tracked? {is_katrina_tracked}")
print(f"After removing Nicole: {remaining_storms}")
In [ ]:
grader.check("q4_membership")

What if we need more than just the category for each storm? We can create separate dictionaries that share the same keys.

In [ ]:
# Multiple dicts tracking different facts about the same storms
storm_wind_mph = {"Milton": 180, "Helene": 140, "Ian": 155, "Idalia": 130, "Nicole": 75}
storm_damage_billions = {"Milton": 50.0, "Helene": 30.0, "Ian": 110.0, "Idalia": 3.5, "Nicole": 2.1}

# Look up everything about one storm across multiple dicts
storm_name = "Ian"
print(f"Hurricane {storm_name}:")
print(f"  Category: {storm_categories[storm_name]}")
print(f"  Wind speed: {storm_wind_mph[storm_name]} mph")
print(f"  Damage: ${storm_damage_billions[storm_name]} billion")

This works, but there's a problem: what if you add a storm to one dict and forget to add it to the others? The dicts can get out of sync. We'll fix this with nested dicts in the next section.

Question 5: Cross-Dict Storm Report (1 point)

Look up information about Hurricane Milton across our tracking dictionaries.

Store Milton's wind speed from storm_wind_mph in milton_wind. Store Milton's category from storm_categories in milton_cat. Then create a formatted string storm_report that reads: "Milton: Category X, Y mph" (where X is the category and Y is the wind speed).

In [ ]:
# YOUR CODE HERE
milton_wind = ...
milton_cat = ...
storm_report = ...

print(storm_report)
In [ ]:
grader.check("q5_cross_lookup")

6. Nested Dictionaries

Instead of keeping multiple separate dicts, we can put all the data for each storm inside a single dictionary. The outer dict maps storm names to inner dicts containing all the details.

In [ ]:
# Nested dict: each value is ANOTHER dict
#
# storms["Milton"]["wind_mph"]
#   ^       ^          ^
#   |       |          |__ second lookup: get wind_mph from Milton's dict
#   |       |__ first lookup: get Milton's entire record
#   |__ the outer dictionary

storms = {
    "Milton": {"category": 5, "wind_mph": 180, "damage_billions": 50.0, "year": 2024, "areas": ["Tampa", "Orlando", "Sarasota"]},
    "Helene": {"category": 4, "wind_mph": 140, "damage_billions": 30.0, "year": 2024, "areas": ["Tallahassee", "Atlanta", "Asheville"]},
    "Ian": {"category": 4, "wind_mph": 155, "damage_billions": 110.0, "year": 2022, "areas": ["Fort Myers", "Orlando", "Cape Coral"]},
    "Idalia": {"category": 3, "wind_mph": 130, "damage_billions": 3.5, "year": 2023, "areas": ["Cedar Key", "Valdosta", "Tallahassee"]},
    "Nicole": {"category": 1, "wind_mph": 75, "damage_billions": 2.1, "year": 2022, "areas": ["Vero Beach", "Daytona Beach", "Orlando"]},
}

# Access with two lookups: storms[name][field]
print(f"Milton's wind speed: {storms['Milton']['wind_mph']} mph")
print(f"Ian's damage: ${storms['Ian']['damage_billions']} billion")
print(f"Helene's year: {storms['Helene']['year']}")
print(f"\nMilton's full record: {storms['Milton']}")

Question 6: Build Storm Records (1 point)

Practice building nested dict entries by hand. Using the values from our flat dicts (storm_categories, storm_wind_mph, storm_damage_billions), create two storm record dictionaries:

milton_record should be a dict with keys "category", "wind_mph", and "damage_billions", with values pulled from the flat dicts for Milton.

helene_record should be the same structure, with values for Helene.

In [ ]:
# YOUR CODE HERE
milton_record = ...
helene_record = ...

print(f"Milton record: {milton_record}")
print(f"Helene record: {helene_record}")
In [ ]:
grader.check("q6_nested_build")

7. Mixed Types as Values

Dict values can be any type — strings, ints, floats, lists, even other dicts. Our storms dict already uses this: the "areas" field is a list inside a dict!

In [ ]:
# Values can be any type — including lists!
print(f"Milton's affected areas: {storms['Milton']['areas']}")
print(f"Type: {type(storms['Milton']['areas'])}")

# You can chain lookups: dict → list → element
print(f"Milton's first affected area: {storms['Milton']['areas'][0]}")
print(f"Number of areas hit by Ian: {len(storms['Ian']['areas'])}")

# You can even loop over a value that's a list
print("\nAll areas hit by Helene:")
for city in storms["Helene"]["areas"]:
    print(f"  - {city}")

Question 7: Navigate Nested Storm Data (1 point)

Using the storms dictionary:

  1. Get the first city in Milton's affected areas list and store it in milton_first_area.
  2. Get Ian's total damage (in billions) and store it in ian_damage.
  3. Get the year Helene occurred and store it in helene_year.
In [ ]:
# YOUR CODE HERE
milton_first_area = ...
ian_damage = ...
helene_year = ...

print(f"Milton's first area: {milton_first_area}")
print(f"Ian's damage: ${ian_damage} billion")
print(f"Helene's year: {helene_year}")
In [ ]:
grader.check("q7_nested_access")

Day 2: Iteration, Comprehension, Sets & Serialization

Quick recap from Day 1:

  • Create a dict: {"key": value, "key": value}
  • Add/update: dict[key] = value
  • Safe lookup: dict.get(key, default)
  • Check membership: key in dict
  • Delete: del dict[key]
  • Nested dicts: dict[outer_key][inner_key]

Now let's learn to loop over dicts, build new dicts with comprehension, work with sets, and save data to files.

In [ ]:
# Re-establish our storm data for Day 2
# (Run this cell even if you completed Day 1 — it ensures the data is loaded)
storms = {
    "Milton": {"category": 5, "wind_mph": 180, "damage_billions": 50.0, "year": 2024, "areas": ["Tampa", "Orlando", "Sarasota"]},
    "Helene": {"category": 4, "wind_mph": 140, "damage_billions": 30.0, "year": 2024, "areas": ["Tallahassee", "Atlanta", "Asheville"]},
    "Ian": {"category": 4, "wind_mph": 155, "damage_billions": 110.0, "year": 2022, "areas": ["Fort Myers", "Orlando", "Cape Coral"]},
    "Idalia": {"category": 3, "wind_mph": 130, "damage_billions": 3.5, "year": 2023, "areas": ["Cedar Key", "Valdosta", "Tallahassee"]},
    "Nicole": {"category": 1, "wind_mph": 75, "damage_billions": 2.1, "year": 2022, "areas": ["Vero Beach", "Daytona Beach", "Orlando"]},
}
print(f"Loaded {len(storms)} storms for Day 2")

8. Iterating Over Dictionaries

Three ways to loop over a dictionary:

  • .keys() — loop over just the keys
  • .values() — loop over just the values
  • .items() — loop over (key, value) pairs — most useful!
In [ ]:
# Reading the .items() syntax
#
# for name, data in storms.items():
#     ^      ^              ^
#     |      |              |__ .items() gives (key, value) pairs
#     |      |__ the value (a nested dict for each storm)
#     |__ the key (the storm name)

# .keys() — just the storm names
print("Storm names:")
for name in storms.keys():
    print(f"  {name}")

# .values() — just the data dicts (no names)
print("\nWind speeds:")
for data in storms.values():
    print(f"  {data['wind_mph']} mph")

# .items() — BOTH name and data (most common!)
print("\nFull report:")
for name, data in storms.items():
    print(f"  {name}: Cat {data['category']}, {data['wind_mph']} mph")

Question 8: Storm Report with Iteration (1 point)

Use a for loop with .items() to build a list of formatted summary strings.

Create storm_summary_lines — a list where each entry is a string like "Milton: 180 mph (Category 5)". Loop through storms.items() and append each formatted string.

Then find the name of the storm with the highest wind speed and store it in strongest_wind_name. (Hint: you can use max() with a key= argument on storms.)

In [ ]:
# \u270f\ufe0f YOUR CODE HERE
storm_summary_lines = ...
...
strongest_wind_name = ...

print("Storm summaries:")
for line in storm_summary_lines:
    print(f"  {line}")
print(f"\nStrongest wind: {strongest_wind_name}")
In [ ]:
grader.check("q8_iteration")

9. Merging Dictionaries

Two ways to combine dictionaries:

  • dict1 | dict2 — creates a new merged dict (Python 3.9+). If both have the same key, dict2 wins.
  • dict1.update(dict2) — modifies dict1 in place, adding/overwriting from dict2.
In [ ]:
# A second tracking station has data on additional storms
station_a = {"Milton": {"category": 5}, "Helene": {"category": 4}}
station_b = {"Francine": {"category": 1}, "Milton": {"category": 4}}  # Different category for Milton!

# | operator creates a new dict (station_b wins on conflicts)
combined = station_a | station_b
print(f"Combined: {combined}")
print(f"Milton's category: {combined['Milton']['category']}")  # 4 (station_b wins)

# .update() modifies in place
station_a_copy = station_a.copy()
station_a_copy.update(station_b)
print(f"\nAfter update: {station_a_copy}")

10. Dictionary Comprehension

Just like list comprehension creates a new list, dict comprehension creates a new dict. Same idea, curly braces instead of square brackets.

In [ ]:
# Reading dict comprehension syntax
#
# {name: cat for name, cat in storm_categories.items() if cat >= 3}
#  ^     ^    ^                                          ^
#  |     |    |                                          |__ filter (optional)
#  |     |    |__ loop variable unpacking
#  |     |__ value expression
#  |__ key expression

# Recall storm_categories from Day 1
print(f"All categories: {storm_categories}")

# Filter: only major hurricanes (category 3+)
major_only = {name: cat for name, cat in storm_categories.items() if cat >= 3}
print(f"Major storms (cat 3+): {major_only}")

# Transform: convert damage from billions to millions
damage_millions = {name: data["damage_billions"] * 1000 for name, data in storms.items()}
print(f"Damage in millions: {damage_millions}")

Question 9: Dict Comprehension (1 point)

Use dictionary comprehension to create two new dictionaries from storms:

  1. major_storms — a dict containing only storms with category 3 or higher. Keys are storm names, values are their category numbers. (Hint: loop over storms.items() and filter on data["category"] >= 3.)

  2. damage_in_millions — a dict mapping each storm name to its damage converted from billions to millions (multiply by 1000). Include all storms.

In [ ]:
# \u270f\ufe0f YOUR CODE HERE
major_storms = ...
damage_in_millions = ...

print(f"Major storms: {major_storms}")
print(f"Damage in millions: {damage_in_millions}")
In [ ]:
grader.check("q9_comprehension")

11. Sets

A set is a collection with two special properties:

  1. No duplicates — Python automatically removes them
  2. No order — you can't access items by index

Sets use curly braces {}, just like dicts. But with no colons, Python knows it's a set.

Watch out: {} creates an empty dict, not an empty set! Use set() for an empty set.

In [ ]:
# Sets automatically remove duplicates
#
# cities = {"Orlando", "Tampa", "Orlando"}
#   ^
#   |__ Python removes the duplicate automatically!
#   Result: {"Orlando", "Tampa"}  (order may vary)

cities = {"Orlando", "Tampa", "Orlando", "Miami", "Tampa"}
print(f"Set: {cities}")
print(f"Length: {len(cities)}")  # 3, not 5!

# Creating an empty set (NOT {} — that's an empty dict!)
empty_set = set()
empty_dict = {}
print(f"\nset() type: {type(empty_set)}")
print(f"{{}} type: {type(empty_dict)}")

# add() and discard()
tracked_cities = set()
tracked_cities.add("Miami")
tracked_cities.add("Tampa")
tracked_cities.add("Miami")  # Duplicate — ignored!
print(f"\nTracked: {tracked_cities}")

tracked_cities.discard("Tampa")
print(f"After removing Tampa: {tracked_cities}")

# Convert a list with duplicates to a set
all_areas = ["Orlando", "Tampa", "Orlando", "Fort Myers", "Orlando"]
unique_areas = set(all_areas)
print(f"\nList: {all_areas}")
print(f"Set (unique only): {unique_areas}")

Question 10: Build City Sets from Storm Data (1 point)

Convert the affected areas lists from our storms dictionary into sets:

  1. Create milton_city_set by converting storms["Milton"]["areas"] to a set.
  2. Create ian_city_set by converting storms["Ian"]["areas"] to a set.
  3. Create all_tracked_cities — a set of every city that appears in any storm's areas. (Hint: start with an empty set and use a loop with .update() or |= to add each storm's areas.)
In [ ]:
# \u270f\ufe0f YOUR CODE HERE
milton_city_set = ...
ian_city_set = ...
all_tracked_cities = ...
...

print(f"Milton cities: {milton_city_set}")
print(f"Ian cities: {ian_city_set}")
print(f"All tracked cities ({len(all_tracked_cities)}): {all_tracked_cities}")
In [ ]:
grader.check("q10_create_sets")

12. Set Operations

Sets support powerful operations for comparing collections. These answer questions like: "Which cities were hit by BOTH storms?" or "Which cities were hit by Milton but NOT Ian?"

In [ ]:
# Set operations — comparing which cities were affected
#
# milton_city_set & ian_city_set  (intersection)
#
#   Milton only    Both     Ian only
#  +-----------+----------+-----------+
#  | Tampa     | Orlando  | Fort Myers|
#  | Sarasota  |          | Cape Coral|
#  +-----------+----------+-----------+

# Union: ALL cities from both storms (no duplicates)
all_cities = milton_city_set | ian_city_set
print(f"Union (all cities): {all_cities}")

# Intersection: cities hit by BOTH storms
both_storms = milton_city_set & ian_city_set
print(f"Intersection (both storms): {both_storms}")

# Difference: cities hit by Milton but NOT Ian
milton_only = milton_city_set - ian_city_set
print(f"Milton only: {milton_only}")

ian_only = ian_city_set - milton_city_set
print(f"Ian only: {ian_only}")

# Symmetric difference: cities hit by one OR the other, but NOT both
one_storm_only = milton_city_set ^ ian_city_set
print(f"One storm only: {one_storm_only}")
In [ ]:
# Subset and superset checks
small_set = {"Orlando"}
big_set = {"Orlando", "Tampa", "Miami"}

print(f"Is {small_set} a subset of {big_set}? {small_set.issubset(big_set)}")
print(f"Is {big_set} a superset of {small_set}? {big_set.issuperset(small_set)}")

Question 11: Compare Storm Paths (1 point)

Using milton_city_set and ian_city_set:

  1. Find the cities that were hit by both Milton and Ian. Store the result in cities_both_storms.
  2. Find the cities that were hit by Milton but not Ian. Store in cities_only_milton.
  3. Find all cities hit by either storm (combined, no duplicates). Store in cities_either_storm.
In [ ]:
# \u270f\ufe0f YOUR CODE HERE
cities_both_storms = ...
cities_only_milton = ...
cities_either_storm = ...

print(f"Both storms: {cities_both_storms}")
print(f"Milton only: {cities_only_milton}")
print(f"Either storm: {cities_either_storm}")
In [ ]:
grader.check("q11_set_ops")

13. Saving Data with JSON

Your hurricane tracker works great, but when you close Python, all the data disappears. JSON (JavaScript Object Notation) lets you save dicts to a file and load them back later.

This builds on the file I/O you learned in Lecture 08 — same open() and with pattern, now with json doing the conversion.

In [ ]:
import json

# json.dumps() converts a dict to a JSON string ("dumps" = dump to string)
sample = {"Milton": {"category": 5, "wind_mph": 180}}
json_string = json.dumps(sample, indent=2)
print("Dict → JSON string:")
print(json_string)
print(f"Type: {type(json_string)}")

# json.loads() converts a JSON string back to a dict ("loads" = load from string)
back_to_dict = json.loads(json_string)
print(f"\nJSON string → Dict: {back_to_dict}")
print(f"Type: {type(back_to_dict)}")
In [ ]:
# Save to a file with json.dump() and load with json.load()
# (Note: dump/load for files, dumpS/loadS for strings — the S means "string")

# Save storms to a JSON file
with open("storms_backup.json", "w") as f:
    json.dump(storms, f, indent=2)
print("Saved storms to storms_backup.json")

# Load storms back from the file
with open("storms_backup.json", "r") as f:
    loaded_storms = json.load(f)
print(f"Loaded {len(loaded_storms)} storms from file")
print(f"Same data? {loaded_storms == storms}")

Question 12: Serialize Storm Data (1 point)

  1. Convert the storms dictionary to a JSON-formatted string using json.dumps() with indent=2 for readability. Store the result in storms_json_string.
  2. Convert storms_json_string back to a dictionary using json.loads(). Store the result in storms_from_json.
In [ ]:
# \u270f\ufe0f YOUR CODE HERE
storms_json_string = ...
storms_from_json = ...

print("JSON string (first 200 chars):")
print(storms_json_string[:200] + "...")
print(f"\nLoaded back: {len(storms_from_json)} storms")
print(f"Round-trip successful? {storms_from_json == storms}")
In [ ]:
grader.check("q12_json")

Summary

Concept Syntax Hurricane Example
Create dict {"key": value} {"Milton": 5, "Helene": 4}
Add/update dict[key] = value storm_categories["Debby"] = 1
Safe lookup dict.get(key, default) storm_categories.get("Katrina", 0)
Membership key in dict "Milton" in storm_categories
Delete del dict[key] del storm_categories["Nicole"]
Nested access dict[key1][key2] storms["Milton"]["wind_mph"]
.keys() for k in dict.keys() Storm names
.values() for v in dict.values() Storm data dicts
.items() for k, v in dict.items() Name + data pairs
Merge dict1 \| dict2 Combine tracking stations
Dict comprehension {k: v for k, v in ...} Filter major storms
Create set {val1, val2} or set() {"Tampa", "Orlando"}
Set union set1 \| set2 All affected cities
Set intersection set1 & set2 Cities hit by both storms
Set difference set1 - set2 Cities hit by only one storm
JSON save json.dumps(dict) Save tracker to string
JSON load json.loads(string) Load tracker from string

Key Takeaways

  1. Dicts map keys to values — like a real dictionary maps words to definitions
  2. Use .get() for safe lookups — avoids KeyError crashes
  3. Nested dicts organize related data — one storm, all its details
  4. .items() is your go-to for looping — gives both key and value
  5. Dict comprehension works just like list comprehension, with {}
  6. Sets are for unique collections — duplicates are removed automatically
  7. Set operations compare groups — union, intersection, difference
  8. JSON serializes dicts to files — save your data, load it later

What's Next?

  • Lab: Capstone project planning and setup
  • Next Lecture: Classes and Object-Oriented Programming

Submitting to Gradescope

This file is saved on your computer — you do not need to download it from Jupyter.

  1. Find the file on your computer:

    • Mac: Open Finder → Documents/CSC115/lecture_notebooks/09_lecture_dictionaries_and_sets/09_lecture_dictionaries_and_sets.ipynb
    • Windows: Open File Explorer → Documents\CSC115\lecture_notebooks\09_lecture_dictionaries_and_sets\09_lecture_dictionaries_and_sets.ipynb
  2. Upload to Gradescope:

    • Go to gradescope.com and open this assignment
    • Click "Submit" and upload the .ipynb file
    • The filename must be exactly 09_lecture_dictionaries_and_sets.ipynb

Do NOT use File > Download in Jupyter — this can rename the file and cause submission errors.


You have completed the Lecture 09: Dictionaries and Sets notebook.


To double-check your work, the cell below will rerun all of the autograder tests.

In [ ]:
grader.check_all()