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..
CodePudding user response:
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.