How to sort a nested dictionary based on sum of inner values

Viewed 245

I am trying to sort a nested dictionary in descending order. Here is my dictionary:

mydict = {'first': {1:10,3:3},'second' : {7:5}, 'thrid': {4:2,5:4}}

and the wanted result is

mydict = {'first':{1:10,3:3}, 'third': {4:2,5:4}, 'second' : {7:5}}

Since the first's inner value's sum is 13, the third is 6, and the second is 5. And I would like to save its keys in the same order in a list

mylist = {1,3,4,7,5}

Here is what I've tried so far

for out_key, out_value in d.items():
  for key,value in sorted(out_value,key=lambda i:sum(i[1]),reverse=True):
      answer.append(key)

This nexted for loop gives me an error saying

'int' object is not subscriptable

I assume that because the key is not string. How should I fix the nested for loop ? Or is there a better way to sort a nested dictionary based on the sum of inner values?

Thank you

1 Answers

You were almost correct. You applied sorted on values instead you need to use d.items(). You can use the key parameter in sorted to tell it to sort by the sum of the values.

mydict = {'first': {1:10,3:3},'second' : {7:5}, 'thrid': {4:2,5:4}}

output = dict(sorted(mydict.items(), key=lambda x: sum(x[1].values()), reverse=True))

print(output)
{'first': {1: 10, 3: 3}, 'thrid': {4: 2, 5: 4}, 'second': {7: 5}}
Related