The random.choice
input is supposed to be a sequence. This causes odd behavior with a dict
, which is not a sequence type but can be subscripted like one:
>>> d = {0: 'spam', 1: 'eggs', 3: 'potato'}
>>> random.choice(d)
'spam'
>>> random.choice(d)
'eggs'
>>> random.choice(d)
'spam'
>>> random.choice(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/random.py", line 274, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
KeyError: 2
Additionally random.choice
doesn't work at all on a set
, and some other containers in the collections
module.
Is there a good reason why random.choice(d)
shouldn't just work in the obvious way, returning a random key?
I considered random.choice(list(d))
and random.sample(d, 1)[0]
but hope there may be more efficient methods. Can random.choice
be improved without degrading the current behavior on sequences?
You can see this thread on the Python bug tracker from 2006 about random.choice not working for sets. It's algorithmically possible to make it work with the same asymptotic efficiency, but it would require either custom support from the set/dict data structures, or a new method in the interface. The python devs don't deem it needed.