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

Published: August 06, 2021

Tags: Python; Dictionary; Random; Sample; 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


returns for example


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


returns for example:


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:


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:


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


returns for example

['e', 'a']