Why Dictionaries?
Exit

Why Dictionaries?

Understand why dictionaries are better than tuples for structured question data

Each question is stored as a tuple with six values: question text, four options, and the correct number. That works — but tuples are positional. To know that q[5] is the correct answer, you have to remember the structure.

You want to add a category to each question. A 7-element tuple is hard to read:

("What is the type of 3.14?", "int", "str", "float", "bool", 3, "types")
#                                                                ^^ index 6

A dictionary makes each field explicit:

{
    "text": "What is the type of 3.14?",
    "options": ["int", "str", "float", "bool"],
    "correct": 3,
    "category": "types"
}

You access each field by name — q["category"] instead of q[6]. Adding or reordering fields does not break anything.

Dictionary syntax

A dictionary is a collection of key-value pairs surrounded by curly braces:

person = {"name": "Alice", "age": 30}
print(person["name"])  # Alice
print(person["age"])   # 30

Keys are usually strings. Values can be any type — including lists:

question = {
    "text": "What does len() return?",
    "options": ["The first item", "The last item", "The number of items", "The sum"],
    "correct": 3,
    "category": "basics"
}
print(question["options"][0])  # The first item
print(question["correct"])     # 3

question["options"] returns the list; [0] accesses the first item.

Next Chapter →