Premier League Predictor: FastAPI & Redis — Chapter 10, Exercise 1 ================================================================== TASK List season 1's gameweeks using SCAN over gameweek:1:*:fixtures, extract the numbers and sort them as strings and as numbers, then compare with the sorted-set answer. Explain what the string order would do to the gameweek menu. SOLUTION keys = [k async for k in r.scan_iter(match="gameweek:1:*:fixtures")] nums = [k.split(":")[2] for k in keys] Real results (season 1 has gameweeks 1, 2, 3 and 10): SCAN keys (unordered): ['gameweek:1:10:fixtures', 'gameweek:1:1:fixtures', 'gameweek:1:2:fixtures', 'gameweek:1:3:fixtures'] sorted as strings: ['1', '10', '2', '3'] sorted as numbers: ['1', '2', '3', '10'] ZRANGE season:1:gameweeks 0 -1 -> ['1', '2', '3', '10'] The pattern itself is fine: 'gameweek:1:*:fixtures' does not match gameweek:10:..., because after 'gameweek:1' the next character must be a colon. But the numbers come out of a key name as strings, so a plain sort puts 10 between 1 and 2, and the menu would read Gameweek 1, Gameweek 10, Gameweek 2, Gameweek 3. The sorted set avoids both steps. Its score is the gameweek number, so Redis keeps it in numeric order and no key-name parsing is needed. The price is that the fixture-creation route must ZADD the gameweek; SCAN would have needed no such bookkeeping but must walk the keyspace on every request. WHY THIS WORKS AS AN ANSWER ---------------------------- It shows the real SCAN output, isolates the string-sort problem from the pattern itself, and states the trade: bookkeeping on write versus a keyspace walk on read.