Home »
Python »
Python programs
Python program to randomize (shuffle) values of dictionary
Here, we are going to learn how to randomize or shuffle the values of a dictionary?
Submitted by Shivang Yadav, on March 25, 2021
A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas.
We have a dictionary consisting of some key-value pairs. We will shuffle the values i.e. the position of keys will be constant but the values attached to the key will be changed randomly.
Example:
Original dictionary:
{'Indore': 2, 'Delhi' : 5, 'Mumbai' : 1, 'Manali' : 3, 'Patna': 8}
Shuffled dictionary:
{'Indore': 1, 'Delhi' : 8, 'Mumbai' : 5, 'Manali' : 2, 'Patna': 3}
To randomize the dictionary values, we will first convert the dictionary to a list then we have used the shuffle() function from the random module to shuffle the values of the list.
These shuffled values are then mapped back with the keys of the dictionary using the zip() method. The output values are then converted to a dictionary using the dict() method.
Algorithm:
- Convert dictionary into list of values
- Randomize the list
- Map the values back with the key values of the dictionary
- Convert it to a dictionary
- Print the dictionary
Program to shuffle values of dictionary in Python
# Python program to shuffle dictionary Values...
# Importing shuffle method from random
from random import shuffle
# Initialising dictionary
myDict = {'Scala': 2, 'Javascript': 5, 'Python': 8, 'C++': 1, 'Java': 4}
# Shuffling Values...
valList = list(myDict.values())
shuffle(valList)
mappedPairs = (zip(myDict, valList))
shuffledDict = dict(mappedPairs)
# Printing the dictionaries...
print("Initial dictionary = ", end = " ")
print(myDict)
print("Shuffled dictionary = ", end = " ")
print(shuffledDict)
Output:
RUN 1:
Initial dictionary = {'Java': 4, 'Scala': 2, 'Python': 8, 'C++': 1, 'Javascript': 5}
Shuffled dictionary = {'Javascript': 4, 'Scala': 1, 'Java': 2, 'C++': 8, 'Python': 5}
RUN 2:
Initial dictionary = {'C++': 1, 'Scala': 2, 'Javascript': 5, 'Java': 4, 'Python': 8}
Shuffled dictionary = {'C++': 8, 'Scala': 1, 'Javascript': 2, 'Java': 5, 'Python': 4}
RUN 3:
Initial dictionary = {'C++': 1, 'Javascript': 5, 'Scala': 2, 'Java': 4, 'Python': 8}
Shuffled dictionary = {'C++': 8, 'Javascript': 4, 'Scala': 2, 'Python': 1, 'Java': 5}
Python Dictionary Programs »