Christian A Christian A -4 years ago 120
Python Question

Sort nested dict on keys

I have run into a little problem with OrderedDicts and sorting.

Currently I have a dict with the following layout:

{"da": {1.0 : [], 1.5 : []}, "en" : {1.2 : [], 1.8 : []}}


What I want to do is sort each nested dict on the key value in a descending order.
So the output should look like this:

{"da": {1.5 : [], 1.0 : []}, "en" : {1.8 : [], 1.2 : []}}


Using OrderedDict proves quite a challenge

outputDict = OrderedDict(sorted(inputDict.items(), key=lambda t: t[1].keys()))


Which gives me:

OrderedDict([('en', {1.2: [], 1.8: []}), ('da', {1.0: [], 1.5: []})])

Answer Source

You can try this:

import collections

a={"da": {1.0 : [], 1.5 : []}, "en" : {1.2 : [], 1.8 : []}}

print {k:collections.OrderedDict(sorted(v.items(),reverse=True)) for k,v in a.items()}

Output:

{'en': OrderedDict([(1.8, []), (1.2, [])]), 'da': OrderedDict([(1.5, []), (1.0, [])])}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download