There is a restriction on random.choice that input must be a sequence. This leads to non-obvious and hairy behavior on the dict :
>>> 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))]
In addition, it does not work at all in set and some other containers in the collections module.
Besides my opinion that this implementation of random.choice is balls (there is no good reason why random.choice(d) should not just work in an obvious way), what is the pythonic way to get a random choice from a non-sequence?
I counted random.choice(list(d)) and random.sample(d, 1)[0] , but I hope there may be other less ugly methods.
Can random.choice decapitate "just work" without violating or drastically reducing the effectiveness of current behavior in sequences?
source share