dimanche 12 juillet 2015

Randomize order of Python OrderedDict

samplesDict is a defaultdict of OrderedDict objects; from Python collections. For each OrderedDict, I would like to create a copy where the order is randomized.

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

But I keep getting a KeyError: 56 at the random.shuffle(i) line; error integer (e.g. 56) is different each time.

To illustrate, one of the OrderedDicts may be

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

And I would like the copy to become

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




Aucun commentaire:

Enregistrer un commentaire