Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking a random element from a non-empty defaultdict

Say I do:

import collections, random
d = collections.defaultdict(list)
d['foo'].append('bar')

Then I pick a random element:

random.choice(d)

Now let's print d:

defaultdict(list, {0: [], 'foo': ['bar']})

Why did random.choice add 0 as a key?

like image 981
usual me Avatar asked Dec 05 '25 08:12

usual me


1 Answers

Internally this is what random.choice does:

def choice(self, seq):
    """Choose a random element from a non-empty sequence."""
    return seq[int(self.random() * len(seq))]

As in your case the length was 1, after multiplication it would result in an number in range [0.0, 1.0) and after applying int()to it you will get 0.

Note that defaultdict will add any key to the dict that was accessed on it:

>>> d = collections.defaultdict(list)
>>> d['i dont exist']
[]
>>> d
defaultdict(<type 'list'>, {'i dont exist': []})

Hence, your dict ended up with 0.

like image 128
Ashwini Chaudhary Avatar answered Dec 07 '25 20:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!