Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

random.choice broken with dicts

$
0
0

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 emptyKeyError: 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?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>