Skip to main content
 首页 » 编程设计

python之随机化Python OrderedDict的顺序

2025年05月04日12leader

samplesDict 是 OrderedDict 对象的默认字典;来自 Python collections .对于每个 OrderedDict,我想创建一个随机顺序的副本。

import collections 
import copy 
import random 
... 
randomizedSamplesDict = copy.deepcopy(samplesDict) 
for k, i in samplesDict.iteritems(): 
  random.shuffle(i) 

但我一直在 random.shuffle(i) 行收到 KeyError: 56;错误整数(例如 56)每次都不同。

为了说明,OrderedDicts 之一可能是

OrderedDict([ 
  ('This is the first key', ['foo', 'baz']), 
  ('And the second key', ['buz', 'baz']), 
  ('Finally the third key', ['bar', 'foo'])]) 

我希望副本成为

OrderedDict([ 
  ('Finally the third key', ['bar', 'foo']), 
  ('This is the first key', ['foo', 'baz']), 
  ('And the second key', ['buz', 'baz'])]) 

请您参考如下方法:

要随机化 OrderedDict,您可以执行以下操作:

od = collections.OrderedDict([('This is the first key', ['foo', 'baz']), ('And the second key', ['buz', 'baz']),  ('Finally the third key', ['bar', 'foo'])]) 
items = od.items() 
random.shuffle(items) 
odrnd = collections.OrderedDict(items) 
ornd 
OrderedDict([('Finally the third key', ['bar', 'foo']), ('This is the first key', ['foo', 'baz']), ('And the second key', ['buz', 'baz'])])