Q:

Python program to randomize (shuffle) values of dictionary

belongs to collection: Python Dictionary Programs

0

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}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

  1. Convert dictionary into list of values
  2. Randomize the list
  3. Map the values back with the key values of the dictionary
  4. Convert it to a dictionary
  5. 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}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to get all unique keys from a set o... >>
<< Python program to get the keys of a dictionary...