Search code examples
pythonsortingdictionarynestedkey

How to sort the keys of a dictionary by the sum of the inner value of its nested dictionary elements?


So I've looked into some similar questions but I couldn't find an answer, suitable for my problem. I have a nested dictionary and I need to sort the keys of the whole dictionary by the sum of the values of the nested dictionaries, but in reversed order:

So from:

dict = {Sarah : {apple: 1, pear: 2}, John: {tomato: 5, cucumber: 5}, Dany: {carrot: 1}}

I need to get to:

dict = {Dany: {carrot:1}, Sarah: {apple: 1, pear: 2}, John: {tomato: 5, cucumber: 5}}

I figured I could maybe do this with dict(sorted(), key, reverse=True), but I am unable to formulate correctly the key because I don't understand how can I access the inner values of the nested dictionaries.

I'd be grateful for your help!


Solution

  • If you have sufficiently high Python (3.7+) version where insertion-order of keys is preserved you can do:

    dct = {
        "Sarah": {"apple": 1, "pear": 2},
        "John": {"tomato": 5, "cucumber": 5},
        "Dany": {"carrot": 1},
    }
    
    dct = dict(sorted(dct.items(), key=lambda k: sum(k[1].values())))
    print(dct)
    

    Prints:

    {'Dany': {'carrot': 1}, 'Sarah': {'apple': 1, 'pear': 2}, 'John': {'tomato': 5, 'cucumber': 5}}
    

    If not, you can use collections.OrderedDict:

    from collections import OrderedDict
    
    dct = OrderedDict(sorted(dct.items(), key=lambda k: sum(k[1].values())))
    print(dct)