0%

Dictionaries and Other Collections

Choose the Right Collection

and already solve two different modeling problems:

  • 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 before?”

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:

Try it

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:

NeedCollectionPromise
items in a meaningful orderlistpositions and order are preserved
named fields or key-value lookupdictionarykeys explain and retrieve values
unique membershipseteach 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 call avoids an ambiguous pair of braces. It is an odd little corner, but at least it is an honest one.

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?