Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort OrderedDict of OrderedDict?

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?

like image 463
Damian Gądziak Avatar asked Nov 07 '11 00:11

Damian Gądziak


People also ask

Can you sort an OrderedDict?

To sort a dictionary by key in Python, use a combination of the sort() and OrderedDict() methods. The OrderedDict() is a method of the Collections module that returns an instance of a dict subclass with a method specialized for rearranging dictionary order.

How do I sort a list of dictionaries in Python?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.


2 Answers

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

like image 82
ThiefMaster Avatar answered Sep 17 '22 18:09

ThiefMaster


>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth'])) 
like image 45
Raymond Hettinger Avatar answered Sep 17 '22 18:09

Raymond Hettinger