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?
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.
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.
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']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With