Derive and Display Categories
Exit

Derive and Display Categories

Build the category list from your data using set, sorted, and join

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Before asking the player to choose a category, the quiz needs to show which categories exist. You could write a string by hand, but that string would go stale the moment you add a question in a new category. The categories are already in your data — read them from there.

set()

A set is a collection that holds each value only once — duplicates are removed automatically:

words = ["apple", "banana", "apple", "cherry", "banana"]
unique = set(words)
# {"apple", "banana", "cherry"}

Ten questions share six categories, so iterating over QUESTIONS produces duplicates. Wrapping that in set() gives you each category exactly once.

sorted()

sorted() takes any collection and returns a new list in alphabetical order:

sorted({"banana", "apple", "cherry"})
# ["apple", "banana", "cherry"]

Sets have no guaranteed order, so sorted() ensures the output is consistent every time.

", ".join()

join() turns a list of strings into a single string, placing the separator between each item:

items = ["apple", "banana", "cherry"]
print(", ".join(items))
# apple, banana, cherry

The string before .join() is the separator — ", " puts a comma and a space between each item.

Putting it together

categories = sorted(set(q["category"] for q in QUESTIONS))
print("Categories: " + ", ".join(categories))

q["category"] for q in QUESTIONS reads every category value from QUESTIONS — ten values, with duplicates. set(...) removes the duplicates. sorted(...) alphabetizes them. ", ".join(categories) formats them as a comma-separated string for the player to read.

Instructions

Print the available categories before each round.

  1. At the top of the while True: loop, before the try/except, add categories = sorted(set(q["category"] for q in QUESTIONS)) — the inner part reads every category from QUESTIONS (with duplicates), set(...) removes duplicates, and sorted(...) alphabetizes them.
  2. On the next line, add print("Categories: " + ", ".join(categories))", ".join(categories) turns the sorted list into a single comma-separated string.