Predict the output
What does this print?
racks = ["tan", "nat", "ant", "bat"]
g: dict[str, list[str]] = {}
for r in racks:
g.setdefault("".join(sorted(r)), []).append(r)
print(len(g), g["ant"])Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 2 ['tan', 'nat', 'ant']
Right: three racks share the sorted key 'ant'; 'bat' makes the second group.
The sorted string is an order-free key, so the dict ends with two keys and appends keep arrival order.
Why not the others?
- B 4 ['ant']. That would happen only if the key kept the original order of letters.
- C 2 ['ant', 'nat', 'tan']. Groups keep the order racks arrive in; nothing sorts the words inside a group.