简体   繁体   中英

Sort a dictionary by values in a nested dictionary

I have dictionary like so:

   dic = {first_a : { first_b : {10, 2} } , second_a : {second_b : {13, 15} } [...] }

I would like to sort the nested dictionary according to the sum of x_a and y_a. I can't get my head around this one, could someone provide an helping hand ? I have tried to use the sorted() function but wasn't able to find the right lambda function to use as key..

Assuming that you meant to have a dictionary like this:

data = {'a': {'b': {2, 10}}, 'c': {'d': {13, 15}}}

You can get what you want like this:

sorted(data, key =lambda k: sum(*dic[k].values()), reverse=True)

However I don't consider this very readable. I would instead do:

def get_sum(k):
    vals, *_ = data[k].values()
    return sum(vals)

sorted(data, key=get_sum, reverse=True)

When I'm looking at code late at night, too many parentheses == too long to figure out what's happening.

Note that I used values() because I didn't know if your inner keys were constant. If they were, life is even easier. Note this operates on and sorts the keys .

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