Lesson
15: Dictionaries (dict) & Registry Lookups — EPA MCLs,
Henry Constants & LCA Footprints
The “Boring Stuff” Problem: Searching Parallel Lists Every Time You Look Up a Chemical Limit
Suppose you store
chemicals = ["Benzene", "TCE", "Nitrate"] and
mcls = [0.005, 0.005, 10.0] in separate lists. Reordering
one breaks the other silently!
A Python dictionary (dict) works like
an organized chemical reference drawer labeled by contaminant key:
epa_mcl_mgL = {"Benzene": 0.005, "TCE": 0.005, "Arsenic": 0.010, "Nitrate_N": 10.0}Looking up epa_mcl_mgL.get("Benzene") jumps
instantaneously to 0.005—zero linear scanning, zero
column-index guessing! Pairing nested dictionaries lets
you bundle MW, MCL, and Henry’s constant together cleanly, OR compile
real inventory impact tables directly from
LCA1_LCIA_Characterization_Factors.csv.
from pathlib import Path
def data_file(name):
"""Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
for p in [
Path("datasets") / name,
Path("../datasets") / name,
Path("../../datasets") / name,
]:
if p.exists():
return p
raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import csv
# Example 1: Nested Environmental Regulatory Registry + Safe .get() Lookup
chem_registry = {
"Benzene": {"MW": 78.11, "MCL_mgL": 0.005, "H_atm_m3_mol": 5.5e-3},
"TCE": {"MW": 131.39,"MCL_mgL": 0.005, "H_atm_m3_mol": 1.03e-2},
"Atrazine": {"MW": 215.68,"MCL_mgL": 0.003, "H_atm_m3_mol": 2.9e-9},
"Nitrate_N": {"MW": 14.01, "MCL_mgL": 10.0, "H_atm_m3_mol": 0.0},
}
water_sample_mgL = {"Benzene": 0.012, "TCE": 0.003, "Nitrate_N": 11.4, "Chloride": 45.0}
print("=== Safe Dictionary Compliance Check (.get guards un-regulated ions!) ===")
for chem, measured in water_sample_mgL.items():
meta = chem_registry.get(chem)
if meta is None:
print(f" {chem:<10s}: {measured:6.3f} mg/L -> No Primary Health MCL (Secondary/Tracer)")
else:
ratio = measured / meta["MCL_mgL"]
strip = "Volatile (Air Stripping Feasible)" if meta["H_atm_m3_mol"] > 1e-4 else "Non-Volatile (GAC / IX / RO)"
print(f" {chem:<10s}: {measured:6.3f} vs MCL {meta['MCL_mgL']:5.3f} ({ratio:4.1f}x) -> {strip}")=== Safe Dictionary Compliance Check (.get guards un-regulated ions!) ===
Benzene : 0.012 vs MCL 0.005 ( 2.4x) -> Volatile (Air Stripping Feasible)
TCE : 0.003 vs MCL 0.005 ( 0.6x) -> Volatile (Air Stripping Feasible)
Nitrate_N : 11.400 vs MCL 10.000 ( 1.1x) -> Non-Volatile (GAC / IX / RO)
Chloride : 45.000 mg/L -> No Primary Health MCL (Secondary/Tracer)
# Example 2 (LCA Track 1 Module 5 Impact Assessment): Dictionary Join Over Real LCIA Factors!
with data_file("LCA1_LCIA_Characterization_Factors.csv").open(encoding="utf-8", newline="") as f:
lcia_db = {r["Flow_ID"]: r for r in csv.DictReader(f)}
# Suppose an electric municipal transit bus lifecycle emits this elementary flow inventory [kg]:
bus_inventory_kg = {
"elem_co2_fos": 48500.0,
"elem_ch4": 145.0,
"elem_n2o": 2.1,
"elem_so2": 34.0,
"elem_nox": 68.0,
}
totals = {"GWP100_kgCO2eq": 0.0, "AP_kgSO2eq": 0.0, "EP_kgPO4eq": 0.0}
for flow_id, qty in bus_inventory_kg.items():
cf = lcia_db[flow_id]
for impact_cat in totals:
totals[impact_cat] += qty * float(cf[impact_cat])
print("\n=== LCA Midpoint Footprint (Dict Lookup Join) ===")
for k, v in totals.items():
print(f" {k:<18s}: {v:10.2f}")=== LCA Midpoint Footprint (Dict Lookup Join) ===
GWP100_kgCO2eq : 53116.50
AP_kgSO2eq : 81.60
EP_kgPO4eq : 8.84
Concept Check Questions
- Why did Example 1 call
chem_registry.get(chem)instead ofchem_registry[chem]onwater_sample_mgLcontaining"Chloride"? - Look at Henry’s constant
Hinchem_registry: why can TCE (H = 1.03e-2 atm*m^3/mol) be stripped cleanly in an aeration tower while Atrazine (2.9e-9) requires Granular Activated Carbon (GAC)? - How does
for k, v in my_dict.items():unpack both keys and values simultaneously?
Guided
Practice Problem 1: Build Sector Wind-Frequency Counter Dictionary
(UCI_Beijing_PM25_Meteorology.csv)
Read UCI_Beijing_PM25_Meteorology.csv, count occurrences
of each wind direction cbwd (NW,
NE, SE, cv) alongside average
\(\text{PM}_{2.5}\) per wind sector
using two accumulator dictionaries (counts and
pm_sums), avoiding .get()
KeyError crashes!
# Guided Practice 1 Starter
counts, sums = {}, {}
with data_file("UCI_Beijing_PM25_Meteorology.csv").open(encoding="utf-8", newline="") as f:
for r in csv.DictReader(f):
if r["pm2.5"] == "NA": continue
w = r["cbwd"]
counts[w] = counts.get(w, 0) + 1
sums[w] = sums.get(w, 0.0) + float(r["pm2.5"])
for w in sorted(counts):
print(f"Wind {w:<4s}: n={counts[w]:6d} hours | Mean PM2.5 = {sums[w]/counts[w]:6.1f} ug/m^3")Wind NE : n= 4756 hours | Mean PM2.5 = 90.2 ug/m^3
Wind NW : n= 13484 hours | Mean PM2.5 = 70.1 ug/m^3
Wind SE : n= 14573 hours | Mean PM2.5 = 110.8 ug/m^3
Wind cv : n= 8944 hours | Mean PM2.5 = 126.2 ug/m^3