0

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

DrPulse
  • 33
  • 1
  • 5

1 Answers1

0

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

netanelrevah
  • 337
  • 4
  • 12
  • I got the error : ```sort = dict(sorted(data.items(), key = lambda x: x[1]['conso'])) KeyError: 'conso' ``` (conso is the real name of the key) With Python 3, which field is used for automatic sorting ? the first ? or is it based on something else ? – DrPulse Nov 08 '21 at 12:30
  • it's not a sorting, it an order (the order of item adding to dict is kept) https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – netanelrevah Nov 08 '21 at 12:38