How to sort OrderedDict of OrderedDict?
You'll have to create a new one since OrderedDict
is sorted by insertion order.
In your case the code would look like this:
foo = OrderedDict(sorted(foo.iteritems(), key=lambda x: x[1]['depth']))
See http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes for more examples.
Note for Python 3 you will need to use .items()
instead of .iteritems()
.
>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))
Sometimes you might want to keep the initial dictionary and not create a new one.
In that case you could do the following:
temp = sorted(list(foo.items()), key=lambda x: x[1]['depth'])
foo.clear()
foo.update(temp)