I have a dictionary
JavaScript
x
2
1
GiftDict = {'Seth':'A', 'Jeremy':'B', 'Ben':'C'}
2
I want to shuffle the values in this dictionary to different keys.
I tried splitting the dictionary into two like this…
JavaScript
1
3
1
person = GiftDict.keys()
2
partner = GiftDict.values()
3
And shuffling the values with
JavaScript
1
3
1
import random
2
random.shuffle(partner)
3
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.
JavaScript
1
15
15
1
import random
2
3
original = {'Seth':'A', 'Jeremy':'B', 'Ben':'C'}
4
result = {'Seth':'A', 'Jeremy':'B', 'Ben':'C'}
5
values = list(original.values())
6
7
# Shuffle values
8
random.shuffle(values)
9
10
# Set values back into the result dictionary
11
for i,j in enumerate(original.keys()):
12
result[j] = values[i]
13
14
# Now the result dictionary contains the original keys and updated values
15