随机重新排序字典

时间:2012-01-09 12:04:36

标签: python random dictionary

让我们考虑一下这本词典

>>> test = {'to have': True, 'to get': False, 'having': False}

想象

>>> test.random_order()
{'having': False, 'to get': False, 'to have': True}

如何随机重新排序?我应该使用OrderedDictrandom.shuffle吗?如果是这样,我该如何组合它们呢?

2 个答案:

答案 0 :(得分:9)

只需将键/值对(项目)随机播放并将其传递给OrderedDict

items = test.items()
random.shuffle(items)
OrderedDict(items)

答案 1 :(得分:3)

从严格意义上讲,您的问题没有意义 - 字典是从设置键到设置值的映射 。因此,他们没有订单,因为集合没有订单。打印字典时看到的顺序是“随机”而不是可信任的。当您将-R标志与现代Python一起使用时,您可以看到随机性:

$ python -R -c 'print dict(foo=10, bar=20, baz=30)'
{'baz': 30, 'foo': 10, 'bar': 20}
$ python -R -c 'print dict(foo=10, bar=20, baz=30)'
{'foo': 10, 'baz': 30, 'bar': 20}

我认为你应该是一个列表,而不是使用字典,因为该数据结构有一个订单。如果您从dict开始,请使用

items = test.items()
random.shuffle(items)

获取已改组(key, value)对的列表。您可以将这些内容传递给OrderedDict,这会为您提供一个字典,其中的键具有与之关联的订单。