Collections: Lists and Dictionaries
Data science and AI rarely operate on isolated numbers or single strings. Real-world systems process collections of data: tables of records, matrices of features, database rows, and JSON payloads from web APIs. In this chapter, you will master Python's two most essential composite data structures: ordered mutable Lists and associative key-value Dictionaries. You will also learn how combining them into 'lists of dictionaries' forms the universal in-memory data model.
- 01Construct, index, slice, and mutate ordered Lists, and master CRUD lifecycle methods (.append, .extend, .insert, .pop, .remove)
- 02Differentiate in-place mutation (.sort()) from non-destructive functional transformation (sorted())
- 03Construct Dictionaries to represent associative key-value pairs and access data defensively using .get() to prevent KeyError crashes
- 04Iterate across dictionaries using .keys(), .values(), and .items() unpacking
- 05Model real-world tabular datasets using lists of dictionaries (representing rows and columns)
- 06Diagnose and prevent critical edge cases: reference aliasing traps, unhashable dictionary keys, and dictionary size mutation during iteration
6.1 Lists: Ordered, Mutable Sequences
Manipulating list elements, slicing sub-lists, and testing membership.
# Creating and modifying a list
risk_thresholds = [30, 60, 80]
print("Initial thresholds :", risk_thresholds)
# In-place mutation via index
risk_thresholds[0] = 35
print("Updated thresholds :", risk_thresholds)
# Slicing lists (produces a new sub-list)
active_tier = risk_thresholds[1:]
print("High-risk tiers :", active_tier)
# Membership check with 'in'
print("Is 60 in thresholds :", 60 in risk_thresholds)- 1.Line 2: Allocates list containing [30, 60, 80].
- 2.Line 6: Mutates index 0 in place from 30 to 35.
- 3.Line 10: Slices indices 1 to end, producing [60, 80].
- 4.Line 14: 60 in risk_thresholds evaluates to True.
Initial thresholds : [30, 60, 80] Updated thresholds : [35, 60, 80] High-risk tiers : [60, 80] Is 60 in thresholds : True
• The Reference Aliasing Trap: Writing `b = a` does NOT copy a list! It merely creates a second variable pointing to the EXACT same memory array! Modifying `b[0] = 999` also changes `a[0]`! To create an independent clone, write: `b = a.copy()` or `b = a[:]` or `b = list(a)`. • IndexError: Just like strings, accessing `scores[10]` when length is 3 raises `IndexError: list index out of range`.
Why it happens: Lists are ordered, mutable collections where items can be accessed, reassigned, or sliced directly by their zero-based index.
6.2 Essential List Methods: append, extend, insert, pop, remove
Adding, removing, popping, and sorting elements in lists.
keywords = ["urgent", "free"]
# .append(val) adds a single item
keywords.append("prize")
print("After append :", keywords)
# .extend(iterable) vs .append(list)
new_terms = ["verify", "account"]
keywords.extend(new_terms)
print("After extend :", keywords)
# .pop() removes and returns last element
last_added = keywords.pop()
print("Popped item :", last_added)
print("After pop :", keywords)
# In-place sort vs non-destructive sorted()
numbers = [85, 12, 94, 45, 68]
sorted_copy = sorted(numbers) # Does NOT mutate numbers
print("sorted() return:", sorted_copy)
print("Original list :", numbers)
numbers.sort() # Mutates numbers in place
print("After .sort() :", numbers)- 1.Line 4: Adds 'prize' to end -> ['urgent', 'free', 'prize'].
- 2.Line 9: Unpacks ['verify', 'account'] into the list.
- 3.Line 13: Removes 'account' and assigns it to last_added.
- 4.Line 18: sorted(numbers) returns a new sorted list without modifying 'numbers'.
- 5.Line 22: numbers.sort() sorts 'numbers' directly in memory.
After append : ['urgent', 'free', 'prize'] After extend : ['urgent', 'free', 'prize', 'verify', 'account'] Popped item : account After pop : ['urgent', 'free', 'prize', 'verify'] sorted() return: [12, 45, 68, 85, 94] Original list : [85, 12, 94, 45, 68] After .sort() : [12, 45, 68, 85, 94]
• The .append() Return Trap: Never write `my_list = my_list.append(5)`! Because `.append()` mutates in-place, it returns `None`. Writing that assignment overwrites `my_list` with `None`, permanently destroying your list! • .remove() Missing Value: Calling `keywords.remove('missing')` crashes with `ValueError: list.remove(x): x not in list`. Check with `if 'missing' in keywords:` first.
Why it happens: Python distinguishes in-place mutators (which return None by convention) from non-destructive functions (which return new objects).
6.3 Dictionaries: Associative Key-Value Mappings
Creating dictionaries, updating keys, and avoiding KeyError crashes.
message = {
"id": 101,
"sender": "hr@datacorp.org",
"risk": 42
}
# 1. Accessing values via square brackets []
print("Sender :", message["sender"])
# 2. Mutating existing key and adding new key
message["risk"] = 75 # Update
message["status"] = "QUARANTINE" # Add new key
print("Updated :", message)
# 3. Defensive lookup with .get(key, default)
# Accessing missing key with [] raises KeyError: message['ip_address']
safe_ip = message.get("ip_address", "UNKNOWN_IP")
print("IP Lookup:", safe_ip)- 1.Line 8: Retrieves 'hr@datacorp.org' using key 'sender'.
- 2.Line 11: Modifies existing key 'risk' from 42 to 75.
- 3.Line 12: Adds new key 'status' with value 'QUARANTINE'.
- 4.Line 17: .get('ip_address', 'UNKNOWN_IP') finds no 'ip_address' key, returning 'UNKNOWN_IP' safely.
Sender : hr@datacorp.org
Updated : {'id': 101, 'sender': 'hr@datacorp.org', 'risk': 75, 'status': 'QUARANTINE'}
IP Lookup: UNKNOWN_IP• KeyError: Writing `print(message['nonexistent'])` halts execution with `KeyError: 'nonexistent'`. Always use `.get()` when working with external data (APIs, web forms, JSON payloads) where fields may be optional or absent. • Unhashable Keys: Attempting `d = {[1, 2]: 'val'}` raises `TypeError: unhashable type: 'list'`. Lists cannot be keys.
Why it happens: Dictionaries use hash tables providing average O(1) constant time lookup.
6.4 Dictionary Iteration: keys(), values(), and items()
Unpacking key-value pairs and formatting dictionary reports.
threat_weights = {
"wire transfer": 35,
"urgent": 20,
"verify account": 25,
"free prize": 30
}
print("=== SECURITY THREAT DICTIONARY ===")
# Unpacking keys and values with .items()
for keyword, weight in threat_weights.items():
print(f" Keyword: '{keyword:<16}' | Threat Weight: +{weight}")
# Calculating aggregate statistics across values
total_possible_score = sum(threat_weights.values())
print(f"\nTotal Max Score Available: {total_possible_score}")- 1.Line 10: .items() yields ('wire transfer', 35), ('urgent', 20), etc.
- 2.Line 11: Formats each keyword and weight with left alignment width :<16.
- 3.Line 14: sum() aggregates all weights (35 + 20 + 25 + 30 = 110).
=== SECURITY THREAT DICTIONARY === Keyword: 'wire transfer ' | Threat Weight: +35 Keyword: 'urgent ' | Threat Weight: +20 Keyword: 'verify account ' | Threat Weight: +25 Keyword: 'free prize ' | Threat Weight: +30 Total Max Score Available: 110
• Mutating Dictionary Size During Iteration: If you try to add or delete keys inside a `for k in d:` loop, Python raises `RuntimeError: dictionary changed size during iteration`! If you need to delete keys, iterate over a static list copy: `for k in list(d.keys()): del d[k]`.
Why it happens: Dictionary view objects provide dynamic windows into the underlying hash map.
6.5 Lists of Dictionaries: The Universal Tabular Data Model
Processing dataset records, computing running averages, and filtering by criteria.
inbox_records = [
{"id": 1, "sender": "manager@work.com", "score": 10, "status": "CLEAN"},
{"id": 2, "sender": "promo@deals.net", "score": 45, "status": "SUSPICIOUS"},
{"id": 3, "sender": "spoof@phish.org", "score": 90, "status": "QUARANTINE"},
{"id": 4, "sender": "hr@work.com", "score": 15, "status": "CLEAN"}
]
print("Total Emails in Inbox:", len(inbox_records))
# Accumulator: Finding all quarantined messages
quarantine_list = []
total_score = 0
for record in inbox_records:
total_score += record["score"]
if record["status"] == "QUARANTINE":
quarantine_list.append(record["sender"])
avg_score = total_score / len(inbox_records)
print(f"Average Inbox Risk : {avg_score:.1f}")
print(f"Quarantined Senders : {quarantine_list}")- 1.Lines 1-6: Defines a 4-row tabular dataset in memory.
- 2.Lines 13-16: Loops over each row, adds to total_score, and filters quarantined senders.
- 3.Line 18: Computes mean risk score (160 / 4 = 40.0).
Total Emails in Inbox: 4 Average Inbox Risk : 40.0 Quarantined Senders : ['spoof@phish.org']
• Heterogeneous/Missing Keys: If row 3 is missing the 'status' key, record['status'] crashes with KeyError! In production, protect access using `record.get('status', 'UNKNOWN')`.
Why it happens: List of dictionaries maps directly to relational database tables and JSON array payloads.
Practice exercise
Work through the exercise before starting the chapter assignment
Exercise 6: Aggregating Student Marks from Dictionaries
basicModify the starter code to loop over the students list, compute the average score across all students, and print the average formatted to 1 decimal place.
Healthcare Emergency Patient Triage & Vitals Registry
A hospital emergency department (ED) at the Center of Excellence needs an automated triage patient registry. Incoming patients are registered as a list of dictionaries with clinical vitals (heart rate, blood pressure, oxygen saturation, pain level). You must compute individual acuity scores, assign triage priority bands, and produce an emergency department census summary.
- Given a list of patient dictionaries:
- [{'id': 'P1', 'name': 'James Hall', 'hr': 130, 'spo2': 88, 'pain': 9},
- {'id': 'P2', 'name': 'Sarah Lin', 'hr': 76, 'spo2': 98, 'pain': 3},
- {'id': 'P3', 'name': 'Robert Diaz', 'hr': 115, 'spo2': 92, 'pain': 8},
- {'id': 'P4', 'name': 'Emma White', 'hr': 82, 'spo2': 99, 'pain': 2}]
- For each patient, calculate Acuity Points based on clinical rules:
- - Oxygen SpO2 < 90%: +40 points | SpO2 between 90% and 94%: +20 points | SpO2 >= 95%: +0 points
- - Heart Rate HR > 120 bpm: +30 points | HR between 100 and 120 bpm: +15 points | HR <= 100: +0 points
- - Severe Pain >= 8: +15 points
- Assign Triage Category based on total acuity points:
- - Points >= 60: 'RED (IMMEDIATE)'
- - Points >= 30: 'YELLOW (URGENT)'
- - Points < 30: 'GREEN (NON-URGENT)'
- Update each patient dictionary in-place by adding the keys 'acuity' and 'category'.
- Calculate departmental summary metrics: Total Patients, Count of RED Acuity patients, and Average Heart Rate.
- Print an aligned ASCII Triage Roster and the final summary metrics.
- 1.Missing vitals: Use .get() with safe fallback defaults in case a vital sign was unrecorded (e.g. pain defaults to 0).
- 2.Boundary values: Patient with SpO2 exactly 90% receives +20 points (use <= and >=).
- 3.In-place dictionary modification: Ensure existing dictionaries in the list are updated with new keys.
# Chapter 6 Assignment: Healthcare Emergency Triage Registry
# Center of Excellence: Data Science & AI
patients = [
{"id": "P1", "name": "James Hall", "hr": 130, "spo2": 88, "pain": 9},
{"id": "P2", "name": "Sarah Lin", "hr": 76, "spo2": 98, "pain": 3},
{"id": "P3", "name": "Robert Diaz", "hr": 115, "spo2": 92, "pain": 8},
{"id": "P4", "name": "Emma White", "hr": 82, "spo2": 99, "pain": 2}
]
# TODO: Step 1 - Iterate through patients and compute acuity score
# TODO: Step 2 - Assign category ('RED (IMMEDIATE)', 'YELLOW (URGENT)', 'GREEN (NON-URGENT)')
# TODO: Step 3 - Store 'acuity' and 'category' keys inside each patient dictionary
# TODO: Step 4 - Calculate summary metrics (total, red_count, avg_hr)
# TODO: Step 5 - Print aligned ASCII Triage Roster
Chapter summary
Key concepts and syntax cards for review
- 01Lists are ordered, mutable sequences; use .append() for single items, .extend() for collections, and .pop() to remove.
- 02b = a aliases the same memory list; use b = a.copy() to create an independent copy.
- 03Dictionaries store key-value mappings with fast O(1) hash table lookup. Keys must be immutable.
- 04Use dict.get(key, default) to prevent KeyError crashes on optional or missing fields.
- 05A list of dictionaries is the industry-standard data structure representing tabular data and API payloads.
lst.append(x), lst.extend(items), lst.pop()List lifecycle manipulation methods.d = {'key': val}, val = d.get('key', default)Dictionary initialization and defensive value lookup.for k, v in d.items(): ...Iterating through key-value pairs simultaneously.Knowledge check
Verify your grasp of the chapter concepts
What will `nums = [1, 2]; nums = nums.append(3)` set `nums` to?
Which of the following can be used as a dictionary key in Python?
What happens if you run: d = {'a': 1}; print(d.get('b', 100))?