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 .iter开发者_运维技巧items() 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
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]
加载中,请稍侯......
精彩评论