samedi 26 septembre 2015

Selecting a Random Value from dictionary in constant time in Python 3?

I know that you can select a random value from a dictionary in several ways.

In Python 2:

random.choice(d.keys())

In Python 3:

random.choice(list(d.keys()))

Nonetheless, both approaches require a transformation, i.e. linear time O(n), to a list before the random selection. For example, I know that in Python 3 d.keys() returns an iterator and I am guessing that in Python 3 the list is created internally from the dictionary.

Is it possible to select a value from a dictionary in constant time, i.e. O(1)?




Aucun commentaire:

Enregistrer un commentaire