[poll] anyone else needs fast random element access off a dictionary?
Peter Hansen
peter at engcorp.com
Tue Feb 11 12:28:49 EST 2003
Michal Vitecek wrote:
>
> for example i'm in need of a _fast_ random element access because i use
> dictionary a) as a mains to have distinct data and b) use the distinct
> data to make a more diversive population in my memetic algorithm (the
> more diversive the population is, the better behaviour of the
> algorithm).
>
> currently one can get a random key stored in a dictionary object like
> this:
>
> random.choice(dict.keys())
>
> the same goes for a random value stored in a dictionary:
>
> random.choice(dict.values())
>
> both those methods have one big drawback - they create a list of either
> keys or values each time a random element is needed which means a very
> noticeable slowdown. [as a sidenote, random.choice() doesn't work with
> dictionaries.]
What is wrong with subclassing to create your own object, with
the property of maintaining a list of the keys, or values, or both,
and even a getRandomItem() method which does the above in a very
speedy manner?
That's what object-oriented programming is all about... in this
case it lets you optimize for the frequent case, even though it
might slow down other situations in a fairly minor way.
-Peter
More information about the Python-list
mailing list