简体   繁体   English

排序深度字典 [Python]

[英]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.我有一个程序,它为 5 个不同环境的每个项目获取 3 个键和值,并从中生成一个 JSON 文件。 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.注 2:项目名称不是“project1”“project2”,它们遵循特定的命名方案,使它们独一无二。

{
    "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.我想让 5 个不同的项目按消耗排序,但无法完成。 I tried to use the lambda function as such :我尝试使用 lambda 函数:

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.我只需要通过升序消费值对 envs 内的项目进行排序。 Got any suggestions ?有什么建议吗? thanks谢谢

If your'e using Python2 try this:如果你使用 Python2 试试这个:

{
    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在 python3 上你不需要 OrderedDict 因为所有的字典都在 python 3 上保持顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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