Random.choice broken with dicts

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))] # raises IndexError if seq is empty KeyError: 2 

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?

+4
source share
1 answer

You can see this thread in the Python error debugger since 2006 about random.choice, which does not work for collections. Algorithmically, you can make it work with the same asymptotic efficiency, but this will require either user support from data structures / data dict, or a new method in the interface. Python developers don't consider it necessary.

+3
source

Source: https://habr.com/ru/post/1479659/


All Articles