Randomly shuffling a dictionary in Python

If you're using Python 3.7, where dicts are officially ordered, you can convert the dict items to a list of tuples for shuffling before converting it back to a dict with the dict() constructor:

import random
d = {'a':1, 'b':2, 'c':3, 'd':4}
l = list(d.items())
random.shuffle(l)
d = dict(l)

You can't reshuffle a dictionary. What you can do is create a list of the dictionary's keys and shuffle that in order to achieve a new arbitrary order in which to access the dictionary's contents:

>>> import random
>>> d = {1:2, 3:4, 5:6, 7:8, 9:10}
>>> d
{1: 2, 3: 4, 9: 10, 5: 6, 7: 8}
>>> keys =  list(d.keys())      # Python 3; use keys = d.keys() in Python 2
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys]
[(1, 2), (5, 6), (7, 8), (9, 10), (3, 4)]
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys]
[(9, 10), (3, 4), (1, 2), (7, 8), (5, 6)]
>>> random.shuffle(keys)
>>> [(key, d[key]) for key in keys]
[(1, 2), (7, 8), (3, 4), (5, 6), (9, 10)]