The way random.choice
works is designed for sequences, not mappings. It picks indices, so will sometimes try cards[0]
, which evidently isn't a valid key. The reason that the error appears random is, of course, because it depends on the value picked by random
!
You can fix this by explicitly choosing from a sequence:
random.choice(list(cards))
To improve your code more generally, note that random
also includes sample
:
rcards = random.sample(list(cards), 3) # pick three random cards
Note that in both cases, we randomly choose keys from the dictionary.