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:

  1. import random
  2. d = {'w': 1, "s": '24', 'wx': 33}
  3. d = sorted(d.items(), key=lambda x: random.random())
  4. print(type(d))
  5. print(d)
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:

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

Leave a Reply