简体   繁体   中英

Sort based Dictionary of Dictionary of Dictionary Values?

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'}]}

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

See demo

d1 = collections.OrderedDict(sorted(d.items()))

This is not working because it is sorting only on the Benefits item. Here you want to sort inner items, so we have to reach the inner items and sort them.

d1 = {'Benefits': {}}
for a_benefit in d['Benefits']:
    d1['Benefits'][a_benefit] = {}
    for a_ben in d['Benefits'][a_benefit]:
        d1['Benefits'][a_benefit][a_ben] = dict(collections.OrderedDict(sorted(d['Benefits'][a_benefit][a_ben].items())))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM