How to select randomly keys from a dictionary in python 3 ?

Active August 06, 2021    /    Viewed 7814    /    Comments 0    /    Edit


Examples of how to select randomly keys from a list in python 3:

Create a dictionary

Lets first create a dictionary in python

d = {'a':1,'b':2,'c':3,'d':4,'e':5}

Select randomly a key using random.choice()

To select a random key from a dictionary, a solution is to use random.choice():

import random

random.choice(list(d))

returns for example

'c'

choice can be used multiple times to select randomly multiple elements:

random.choice(list(d))

returns for example:

'e'

To create a list of keys random selected randomly, a solution is to use a list comprehension:

r = [random.choice(list(d)) for i in range(2)]

returns for example

['a', 'f']

Another example with 10 elements selected radnomly:

r = [random.choice(list(d)) for i in range(10)]

returns for example

['e', 'd', 'b', 'b', 'c', 'b', 'a', 'a', 'b', 'c']

Note: to get always the same output, a solution is to use a seed:

random.seed(42)

r = [random.choice(list(d)) for i in range(10)]

will always returns the same.

Create a random sample using random.sample()

Another solution is to create a sample without replacement:

random.sample(list(d),n)

where l is the list and n the sample's size ( n <= len(l) ).

random.sample(list(d),2)

returns for example

['e', 'a']

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount