3/14/2023

python dict shuffle

shuffle dict order 


.

import random

my_dict = {'apple': 2, 'banana': 3, 'orange': 1, 'kiwi': 4}

# Convert the dictionary to a list of tuples and shuffle it
items = list(my_dict.items())
random.shuffle(items)

# Convert the shuffled list back to a dictionary
shuffled_dict = {k: v for k, v in items}

print(shuffled_dict)

..


Thank you.


No comments:

Post a Comment