Dictionaries and Other Collections
Choose the Right Collection
a list keeps items in a useful order;
a dictionary gives values meaningful labels.
One more collection earns a place in this course because it answers a different question: “Have I seen this
Set: keep each value once
A set stores unique values. If a value appears twice in a set literal, the set still keeps only one copy:
The membership check prints True. The printed order of the set may vary, so do not use a set when first, second, or last matters. Its promise is uniqueness, not position.
That makes a set useful for questions such as:
Which tags have appeared?
Has this username already been used?
Which quiz categories are present?
Choose by the promise you need
Suppose a quiz program stores three kinds of data:
question_order = ["warm-up", "loops", "debugging"]
question = {
"prompt": "Which keyword ends a loop?",
"answer": "break",
}
seen_categories = {"basics", "loops"}
Each collection says something different:
| Need | Collection | Promise |
|---|---|---|
| items in a meaningful order | list | positions and order are preserved |
| named fields or key-value lookup | dictionary | keys explain and retrieve values |
| unique membership | set | each value appears at most once |
A list can contain duplicate tags. A dictionary could invent labels for them. Neither is wrong Python, but the set states the rule directly.
The empty-set wrinkle
An empty list is [] and an empty dictionary is {}. An empty set uses set():
seen_categories = set()
Python already gave {} to dictionaries, so the
This is recognition-level knowledge. You should be able to choose a set when uniqueness is the problem and use in to ask about membership. More advanced set operations can wait until a program actually needs them.
Which collection best stores unique tags when their order does not matter?