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

Published: August 06, 2021

Tags: Python; Dictionary; Random; Sample;

DMCA.com Protection Status

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