I have a dictionary like this
d = { 'Benefits': { 1: { 'BEN1': { 'D': [{'description': 'D1'}], 'C': [{'description': 'C1'}] } }, 2: { 'BEN2': { 'D': [{'description': 'D2'}], 'C': [{'description': 'C2'}] } } } }
I am trying to sort dictionary based on KEY OF LAST VALUES(LIST).
FOR EXAMPLE
I am looking for get dictionary value like ‘C’ IN first and ‘D’ in second
I’m trying to get correct order. Here is code:
d1 = collections.OrderedDict(sorted(d.items()))
Unfortunately didn’t get correct result
This is my expected output
{'Benefits': {1: {'BEN1': {'C':[{'description': 'C1'}], 'D': [{'description': 'D1'}] } }, 2: {'BEN2': {'C': [{'description': 'C2'}], 'D': [{'description': 'D2'}] } } } }
I am using python 3.5 . I am trying to get order like this
{'C':[{'description': 'C1'}], 'D': [{'description': 'D1'}]}
Advertisement
Answer
The following code will sort any dictionary by its key and recursively sort any dictionary value that is also a dictionary by its key and makes no assumption as to the content of the dictionary being sorted. It uses an OrderedDict
but if you can be sure it will always run on Python 3.6 or greater, a simple change can be made to use a dict
.
from collections import OrderedDict d = { 'Benefits': { 1: { 'BEN1': { 'D': [{'description': 'D1'}], 'C': [{'description': 'C1'}] } }, 2: { 'BEN2': { 'D': [{'description': 'D2'}], 'C': [{'description': 'C2'}] } } } } def sort_dict(d): items = [[k, v] for k, v in sorted(d.items(), key=lambda x: x[0])] for item in items: if isinstance(item[1], dict): item[1] = sort_dict(item[1]) return OrderedDict(items) #return dict(items) print(sort_dict(d))