简体   繁体   中英

Sorting deep dictionary [Python]

I have a program that takes 3 keys and values per project for 5 different environments and makes a JSON file out of it. It looks like this (simplified).

Note : the number of project can change and they can't have the same name inside different environments, they have a tag at the end of them.

Note 2 : The project name aren't "project1" "project2", they follow a specific naming scheme making them unique.

{
    "env_preprod": {
        "project1": {
            "consumption last month": 127.283851, 
            "quotas": 200, 
            "consumption ": 117.657964
        }, 
        "project2": {
            "consumption last month": 0.000891, 
            "quotas": 200, 
            "consumption ": 0.00018
        }
    }
    "env_prod": {
        "project1": {
            "consumption last month": 127.283851, 
            "quotas": 200, 
            "consumption ": 117.657964
        }, 
        "project2": {
            "consumption last month": 0.000891, 
            "quotas": 200, 
            "consumption ": 0.00018
        }
    }
}

I want to have the projects in the 5 different behing sorted by consumption but couldn't get it done. I tried to use the lambda function as such :

sort = dict(sorted(data.items(), key = lambda x: x[1]['consumption']))

I also tried this but I didn't sort values:

res = {key : dict(sorted(val.items(), key = lambda ele: ele[1]))
       for key, val in data.items()}

I think at this point only a loop would do it but can't figure it out properly right now. I just need to sort the projects inside envs by ascending values of consumption. Got any suggestions ? thanks

If your'e using Python2 try this:

{
    key: OrderedDict(
        sorted(value.items(), key=lambda x: x[1]['consumption '])
    ) 
    for key, value in data.items()
}

on python3 you don't need OrderedDict because all dicts keep order on python 3

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