Search code examples
pythonsortingnestedordereddictionary

Sorting Python OrderedDict in "heavily nested" structure


I have the following Python dictionary and I'm trying to sort it as an OrderedDict.

fruits = {
    "apple": {
        "details": {
            "color": "green", 
            "dim": 100
        },
        "types": {
            "Akane": {
                "taste": "acceptable",
                "sort": 1
            },
            "McIntosh": {
                "taste": "delicious",
                "sort": 0
            }, 
            "Ambrosia": {
                "taste": "ok",
                "sort": 1
            }
        }
    },         
    "pear": {
    }, 
    "banana": {
    }, 
}

Basically I want to sort the different appleTypes within that subdictionary by the "sort" value of each appleType. In the end the ordered dictionary ideally should look like this:

fruits_sorted = {
    "apple": {
        "details": {
            "color": "green", 
            "dim": 100
        },
        "types": {
            "Akane": {
                "taste": "acceptable",
                "sort": 1
            },
            "Ambrosia": {
                "taste": "ok",
                "sort": 1
            },
            "McIntosh": {
                "taste": "delicious",
                "sort": 0
            }
        }
    },         
    "pear": {
    }, 
    "banana": {
    }, 
}

I've been playing around with the sorted function, but I couldn't quite get it right, I'm not sure how to implement the sorting in that nested structure.

fruits_sorted = OrderedDict(sorted(fruits.items(), key=lambda x: x[1]))

Any help is highly appreciated!


Solution

  • Your solution is very close; you need to have:

    from collections import OrderedDict
    
    apple_types = fruits['apple']['types']
    types_sorted = OrderedDict(sorted(apple_types.items(), key=lambda x: -x[1]['sort']))
    

    Now, types_sorted has the apple types in the sorted order you wanted. You can put it back into the original dictionary if you wish.

    Does that answer your question?