How to Shuffle a Dictionary in Python

A Python dictionary is a built-in data type that allows for the storage of data in key-value pairs. However, unlike lists or tuples, dictionaries don’t maintain any order of their elements. This is because the main point of dictionaries is to give fast access to values based on keys rather than their positional order.

For this reason, dictionary types do not include any method to shuffle its elements. But, nothing to worry about – Python gives several workarounds that we can use to shuffle dictionary items.

Using the random Module

One option we have to shuffle dictionary items is by using the random.shuffle() function together with dictionary methods that return lists. The idea here is to convert the dictionary into a list, shuffle the list items, and recreate the dictionary.

The above piece of code creates a shuffled dictionary dict2 using the keys of dict1. First, we extract the keys from dict1 and store them in a list named key_list. Then, we randomly shuffle the key_list. Finally, we recreate the dictionary from the shuffled keys and the original dictionary.

After running this code, our shuffled dictionary dict2 could be something like this:

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

It’s important to note that running the script will result in a different shuffled dictionary since the random.shuffle() function shuffles items non-deterministically.

Full Code

Below is the complete code we’ve used to shuffle items of a dictionary in Python.

Conclusion

Even though Python does not provide a built-in method to shuffle elements of a dictionary, one can shuffle dictionary items by taking advantage of the random module’s shuffle function. Do keep in mind that every time you run the script, the output will be different because the random.shuffle() function shuffles the items in the list in an unpredictable manner. However, it’s a flexible and useful way to get a shuffled dictionary in Python.