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


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


Card image cap

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). is visited by millions of people each year and it will help us to maintain our servers and create new contents.