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
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

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)
		   
'X'
>>> rand_key(data)
		   
'P'
>>> rand_key(data)
		   
'D'
>>> rand_key(data)
		   
'G'
>>> rand_key(data)
		   
'H'
>>> data[rand_key(data)]
		   
'x'
>>> data[rand_key(data)]
		   
'w'
>>> data[rand_key(data)]
		   
'n'
>>> data[rand_key(data)]
		   
'h'

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]
		   
'L'
>>> import random
		   
>>> dataindex[random.randrange(len(dataindex))]
		   
'Y'
>>> dataindex[random.randrange(len(dataindex))]
		   
'O'

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

greetings,

just a check, is this:

random.choice(list(data.keys()))

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

yours,

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

<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campai
gn=sig-email&utm_content=webmail>
Garanti
sans virus. www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campai
gn=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
--
https://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list