Lesson explanation
After this lesson, you will be able to:
Choosing a data structure is a design decision. Use a list when order and repeated values matter; a tuple for a fixed record; a set for uniqueness and membership; and a dictionary for key-based lookup.
A set alone is not an ordered result. When you want the first occurrence of each item in its original order, use a set to remember what you have seen and a list to collect the results. This combines the strengths of both structures.
You can also connect collections: loop through a list of records, use a dictionary to look up details by key, and add one transformed result to a new list. For a multi-step report, separate the work into normalization, validation, counting, and presentation. Return the finished data when writing a reusable function.
No new advanced Python syntax is required here. The challenge is choosing the right representation and combining techniques from this unit and Python Basics for Programmers.
steps = ["build", "test", "build"]
release = ("v3", "eu")
tags = {"api", "worker", "api"}
ports = {"api": 8080, "worker": 9000}
print(len(steps))
print(release[0])
print(len(tags))
print(ports["worker"])Output:
3
v3
2
9000Each collection expresses a different need: sequence, fixed record, uniqueness, or lookup.
raw = ["api", "worker", "api", "cache"]
seen = set()
unique = []
for name in raw:
if name not in seen:
seen.add(name)
unique.append(name)
print(unique)Output:
['api', 'worker', 'cache']The list retains order; the set remembers which names were already added.
jobs = [{"name": "search"}, {"name": "backup"}]
owners = {"search": "Maya"}
labels = []
for job in jobs:
labels.append(f"{job['name']}: {owners.get(job['name'], 'unassigned')}")
print(labels)Output:
['search: Maya', 'backup: unassigned']The dictionary provides an optional lookup for each record.
results = [("api", "passed"), ("worker", "failed"), ("cache", "passed")]
counts = {"passed": 0, "failed": 0}
for service, state in results:
if state in counts:
counts[state] += 1
print(f"Passed: {counts['passed']}")
print(f"Failed: {counts['failed']}")Output:
Passed: 2
Failed: 1The fixed count dictionary keeps reporting predictable even when a category has zero events.
| Need | Structure or technique |
|---|---|
| Ordered values, including repeats | list |
| Fixed-size record | tuple |
| Unique membership tracking | set |
| Lookup details by identifier | dict |
| Ordered unique values | List + set together |
| Optional related data | mapping.get(key, default) |
if mapping.get(key) to check existence drops valid falsy values.