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().

Leave a Comment