How to Shuffle a Dictionary in Python?

Estimated read time 2 min read

Dictionaries are unordered collections of key-value pairs in Python, so they do not have a concept of order that can be shuffled. However, you can shuffle the keys of a dictionary and use them to access the corresponding values in a random order. Here’s an example of how to shuffle the keys of a dictionary in Python:

import random

# Define the dictionary to be shuffled
mydict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

# Get the keys of the dictionary
keys = list(mydict.keys())

# Shuffle the keys
random.shuffle(keys)

# Print the values in the shuffled order
for key in keys:
    print(mydict[key])

In this example, the keys of the dictionary mydict are obtained using the keys() method, and then converted to a list using the list() function. The random.shuffle() function is then used to shuffle the list of keys in a random order. Finally, the shuffled keys are used to access the corresponding values of the dictionary in a random order, by looping over the shuffled keys and using them to index the dictionary using the square bracket notation.

When you run this code, you will see the values of the dictionary mydict printed in a random order. Note that this technique can be used to access the values of any dictionary in a random order, by shuffling its keys and using them to access the corresponding values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply