Search code examples
pythonpython-3.xdefaultdict

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?


Solution

  • 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.