How to shuffle randomly dictionary keys in python 3 ?


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():
        print(key,value)

returns

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)

random.shuffle(key_list)

d2 = {}

for key in key_list:
        print(key,d[key])
        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)).

Example:

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

returns here

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

References