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)?
EDIT: For the comments so far, I think that it is not possible, at least not in a straight forward fashion. Auxiliary structures are required.
EDIT 2: I thought that the dictionary could have a random choice in constant time since internally it is a hash table, i.e. internally it has to have an array or something similar. Of course, it depends on the internal implementation, but theoretically I think it is possible.