简体   繁体   中英

Sort a complex python dictionary?

I'm sorry if that question has already been asked before, I read some topics but it didn't help me so far.

I get this JSON response from a software API :

 {
    u 'code': 0, u 'message': u 'Found: 367', u 'objects': {
        u 'ApplicationSolution::15056': {
            u 'fields': {
                u 'id': u '15056',
                u 'name': u 'R'
            },
            u 'message': u '',
            u 'code': 0,
            u 'class': u 'ApplicationSolution',
            u 'key': u '15056'
        },
        u 'ApplicationSolution::15758': {
            u 'fields': {
                u 'id': u '15758',
                u 'name': u 'Z'
            },
            u 'message': u '',
            u 'code': 0,
            u 'class': u 'ApplicationSolution',
            u 'key': u '15758'
        },
        u 'ApplicationSolution::15053': {
            u 'fields': {
                u 'id': u '15053',
                u 'name': u 'E'
            },
            u 'message': u '',
            u 'code': 0,
            u 'class': u 'ApplicationSolution',
            u 'key': u '15053'
        },
        u 'ApplicationSolution::15050': {
            u 'fields': {
                u 'id': u '15050',
                u 'name': u 'C'
            },
            u 'message': u '',
            u 'code': 0,
            u 'class': u 'ApplicationSolution',
            u 'key': u '15050'
        },
}

I would like to sort this response with ApplicationSolution name (objects > ApplicationSolution:xxxxx > fields > name). I try to do this with sorted but I didn't find the right syntax :(

Anyone could help me please ?

Thank you so much !

I would first convert the dictionary to a list of 2-tuples, and then sort the list with the appropriate field. It can be as simple as (assuming the global dict is called j ):

sorted([(k,v) for k,v in j['objects'].items()], key=(lambda x: x[1]['fields']['name']))

If d is your dict, then

def fieldname((k, v)):
    return v['fields']['name']
d['objects'] = list(sorted(d['objects'].items(), key=fieldname))

would do it in-situ.

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