random choice from dictionary
MRAB
python at mrabarnett.plus.com
Sun Dec 23 16:21:29 EST 2018
On 2018-12-23 19:52, Avi Gross wrote:
> There are quite a few places the new pythonic way of doing things requires
> extra steps to get an iterator to expand into a list so Abdul-Rahmann
> probably is right that there is no easy way to get a random key from a
> standard dictionary. Other than the expected answers to make a customized
> dictionary or function that provides the functionality at the expense for
> potentially generating a huge list of keys in memory, I offer the following
> as an alternative for large dictionaries and especially if they have large
> keys.
>
> The following is a function that iterates over the dictionary one key at a
> time and when it reaches a random one, it returns the key without further
> evaluation. On the average, it takes N/2 iterations for N keys. Asking to
> make a list(data) may be efficient in terms of time and indexing is fast but
> space is used maximally unless it just points to existing storage.
>
> Here is one way to do the function. Some might use an emum instead.
>
> def rand_key(data):
> """Get a random key from a dict without using all of memory."""
> import random
> randy = random.randrange(len(data))
> this = 0
> for key in data:
> if (this == randy):
> return(key)
> this += 1
>
[snip]
You might as well use 'enumerate' there:
def rand_key(data):
"""Get a random key from a dict without using all of memory."""
import random
randy = random.randrange(len(data))
for this, key in enumerate(data):
if this == randy:
return key
Or you could use 'islice':
def rand_key(data):
"""Get a random key from a dict without using all of memory."""
import itertools
import random
randy = random.randrange(len(data))
return list(itertools.islice(data, randy, randy + 1))[0]
More information about the Python-list
mailing list