I have a dictionary
GiftDict = {'Seth':'A', 'Jeremy':'B', 'Ben':'C'}
I want to shuffle the values in this dictionary to different keys.
I tried splitting the dictionary into two like this…
person = GiftDict.keys() partner = GiftDict.values()
And shuffling the values with
import random random.shuffle(partner)
But I keep getting a type error:’dict_values’ object is not subscriptable
I want to recreate the dictionary but with shuffled values. Is this the correct way to get there? Any tips? Thanks!
Advertisement
Answer
As mentioned here you can’t reshuffle a dictionary. However, you can create a list of the dictionary’s values, shuffle that, and then create a new dictionary with the same keys and updated values.
import random original = {'Seth':'A', 'Jeremy':'B', 'Ben':'C'} result = {'Seth':'A', 'Jeremy':'B', 'Ben':'C'} values = list(original.values()) # Shuffle values random.shuffle(values) # Set values back into the result dictionary for i,j in enumerate(original.keys()): result[j] = values[i] # Now the result dictionary contains the original keys and updated values