random choice from dictionary

Avi Gross avigross at verizon.net
Sun Dec 23 14:52:17 EST 2018

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

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):
        this += 1

Here is a sample showing it running:

>>> import string
>>> data= { key : value for (key, value) in zip(string.ascii_uppercase,
string.ascii_lowercase) }
>>> data
{'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd', 'E': 'e', 'F': 'f', 'G': 'g', 'H':
'h', 'I': 'i', 'J': 'j', 'K': 'k', 'L': 'l', 'M': 'm', 'N': 'n', 'O': 'o',
'P': 'p', 'Q': 'q', 'R': 'r', 'S': 's', 'T': 't', 'U': 'u', 'V': 'v', 'W':
'w', 'X': 'x', 'Y': 'y', 'Z': 'z'}
>>> rand_key(data)
>>> rand_key(data)
>>> rand_key(data)
>>> rand_key(data)
>>> rand_key(data)
>>> data[rand_key(data)]
>>> data[rand_key(data)]
>>> data[rand_key(data)]
>>> data[rand_key(data)]

Of course it depends on what you want to do. If getting random keys
repeatedly, it would be best to do things like make another dictionary with
the new key being integers from 0 to the length and the new values to be the
old keys. You can then look up a random index to get a random key.

>>> dataindex = { index: key for (index, key) in enumerate(data)}
>>> dataindex
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9:
'J', 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R',
18: 'S', 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}
>>> dataindex[11]
>>> import random
>>> dataindex[random.randrange(len(dataindex))]
>>> dataindex[random.randrange(len(dataindex))]

Again, depending on your needs, some solutions may be worth extra code, some
may not.

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Abdur-Rahmaan Janhangeer
Sent: Sunday, December 23, 2018 1:17 AM
To: Python <python-list at python.org>
Subject: random choice from dictionary


just a check, is this:


the only way to get a random key from a dictionary? if not any plan to a
more convenient naming?


Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ Mauritius

sans virus. www.avast.com

More information about the Python-list mailing list