How to sort OrderedDict of OrderedDict?

PythonSortingNestedOrdereddictionary

Python Problem Overview


I'm trying to sort OrderedDict in OrderedDict by 'depth' key. Is there any solution to sort that Dictionary ?

OrderedDict([  (2, OrderedDict([    ('depth', 0),      ('height', 51),     ('width', 51),       ('id', 100)  ])), 
  (1, OrderedDict([    ('depth', 2),      ('height', 51),     ('width', 51),      ('id', 55)  ])), 
  (0, OrderedDict([    ('depth', 1),      ('height', 51),     ('width', 51),      ('id', 48)  ])),
]) 

Sorted dict should look like this:

OrderedDict([  (2, OrderedDict([    ('depth', 0),      ('height', 51),     ('width', 51),       ('id', 100)  ])), 
  (0, OrderedDict([    ('depth', 1),      ('height', 51),     ('width', 51),      ('id', 48)  ])),
  (1, OrderedDict([    ('depth', 2),      ('height', 51),     ('width', 51),      ('id', 55)  ])), 
]) 

Any idea how to get it?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))

Solution 3 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDamian GądziakView Question on Stackoverflow
Solution 1 - PythonThiefMasterView Answer on Stackoverflow
Solution 2 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 3 - PythonjohnsonView Answer on Stackoverflow