随机化字典排序

时间:2014-05-26 20:39:55

标签: python python-2.7 random dictionary

我一直在考虑这个问题,但我没有得出任何结论(对于Python来说还不是很好)。

我的字典看起来像这样:

{1: [dog, animal], 2: [square, shape], 3: [red, color]}

我正在打印出值,但字典按数字排序,这很好,但我想随机化它,所以我打印出这样的东西:

3
red
color
1
dog
animal
2
square
shape

我知道这个列表对于这种情况会更理想,但这些数据来自我无法改变的现有结构。也许重新编号键可以解决问题吗?

2 个答案:

答案 0 :(得分:6)

字典已经按任意顺序列出,它们没有固定的顺序。请参阅Why is the order in dictionaries and sets arbitrary?任何秩序感都是巧合,取决于字典的插入和删除历史。

也就是说,使用random.shuffle()进一步确保洗牌后的列表非常容易:

import random

items = yourdict.items()
random.shuffle(items)

for key, value in items:
    print key
    print '\n'.join(value)

答案 1 :(得分:4)

您可以随机化按键:

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