Randomize or Shuffle a Python Dictionary – Python Tutorial

By | December 24, 2020

Sometimes, we need shuffle a python dictionary. In this tutorial, we will introduce you how to do.

How to randomize a python dictionary?

As to python list, we can use random.shuffle() function to randomize it. Here is an tutorial:

Understand Python random.shuffle(): Randomize a Sequence

However, python dictionary can not be used in this function.

We can use code below:

import random

d = {'w': 1, "s": '24', 'wx': 33}

d = sorted(d.items(), key=lambda x: random.random())
print(type(d))
print(d)

This code will sort a python dictionary randomly. Run this code, you may get a result like:

<class 'list'>
[('w', 1), ('wx', 33), ('s', '24')]

Leave a Reply