CSc 120: Shuffle a Dictionary Expected Behavior Write a function shuffle_dict(so
ID: 3878658 • Letter: C
Question
CSc 120: Shuffle a Dictionary Expected Behavior Write a function shuffle_dict(somedict) that behaves as tollows. Its argument somedict is a dictionary. This function returns a new dictionary constructed as follows: 1. Let sorted keys be the sorted list of the keys of somedict. 2. Let sorted_vals be the sorted list of the values that these keys are mapped to in somedict. 3. Construct a dictionary shuffled dict that maps sorted keys to sorted vals[0], sorted keys1 4. Return the dictionary shuffled dict so constructed. to sorted vals, sorted keys12] to sorted vas21,.. sorted keys[n] to sorted vals[n ] Note: You can get the set of values in a dictionary somedict using sonedict.values ().This is analogous to the keys( method that gives the keys in a dictionary. In each case, you then need to use listto obtain a list Examples 1. Suppose onedict . { . a' : 12 , : 93, 'c' 47). Then, sorted keys is the ist of keys of this dctionary in sorted order, so sorted keys 'a', b, c' sorted _vals is the sorted list of values that these keys are mapped to, i.e., sorted vals 12, 47, 93) Then the value returned by the function shuffle_dict is the dictionary ( 12, 'b47. 93 2. Let somedict- 345: pqr, 456: 'abc',123: 'wxy, 234:ijk'. Then: sorted keys123, 234, 345, 456] So the value returned by this function is the dictionary (123 'abc, 234: 'ijk, 345 pq,456 wxy 3. Let sonedict _ { (11,22,33):'uw', (11,43,27):'abe", (22,11,19):1m' },Then: sorted keys(11, 22, 33), (11, 43, 27), (22, 11, 19)1 sorted vals 'aba'lmn', uvw' So the value returned by this function is the dictionary (11,22,33): 'abc,111.43,27)'1mn'.(22,11.19):)Explanation / Answer
def shuffle_dict(somedict):
sorted_keys=list(somedict.keys())
sorted_values=list(somedict.values())
sorted_keys.sort()
sorted_values.sort()
shuffle_dict={}
for i in range(len(sorted_keys)):
shuffle_dict[sorted_keys[i]]=sorted_values[i];
return shuffle_dict
print(shuffle_dict({'a':12,'b':93,'c':47}))