How to shuffle randomly dictionary keys in python 3 ?

Published: August 06, 2021

Tags: Python; Dictionary; Random; Shuffle; Sample; Protection Status

Examples of how to shuffle randomly dictionary keys in python 3:

Create a dictionary

Lets first create a dictionary in python:

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

to iterate over keys and values of a dictionary:

for key,value in d.items():


a 1
b 2
c 3
d 4
e 5

Shuffle randomly dictionary keys

By default python dictionary are not ordered object. However, it it possible to shuffle dictionary keys to change the order of which keys and values are printed:

key_list = list(d)


d2 = {}

for key in key_list:
        d2[key] = d[key]

returns for example

c 3
e 5
d 4
b 2
a 1

Create a dictionary sample

To create a dictionary sample, a solution is to do:

import itertools

d_sample = dict(itertools.islice(d2.items(), n))

where n is the sample size (n <= len(d)).


d_sample = dict(itertools.islice(d2.items(), 3))

returns here

 {'a': 1, 'd': 4, 'e': 5}