Hossein
Hossein

Reputation: 41831

Randomizing a dictionary in python

I know you might say that dictionaries are not in any order naturally, but I have a large dictionary keys are numbers and some string as their values. The keys start from 0. for example: x={0:'a',1:'b',2:'c'}. I am using .iteritems() to go over my dictionary in a loop. however, this is done in the exact order of the keys 0,1,2. I want this to be randomized. so for example my loop prints this: 1:'b',2:'c',0:'a'. i need help. thanks

Upvotes: 2

Views: 8757

Answers (1)

AKX
AKX

Reputation: 168957

Use random.shuffle. Also, the key iteration order of a dictionary is not guaranteed by any means - you just happened to get (0, 1, 2).

import random
keys = my_dict.keys()
random.shuffle(keys)
for key in keys:
    print key, my_dict[key]

Upvotes: 11

Related Questions