I have a dictionary which has another dictionary as a value. How can I sort it first by key(ascending), and second by the value of the second dictionary(descending)?
my_dict = {'B':{'contest':30, 'contest_two':50, 'contest_three':40}
'A':{'contest_four':50, 'contest_five':60, 'contest_six':70}}
I want to get this :
my_dict = {'A':{'contest_six':70, 'contest_five':60, 'contest_four':50}
'B':{'contest_two':50, 'contest_three':40, 'contest':30 }}
I tried this my_dict = dict(sorted(my_dict.items(), key=lambda x: (x[0],x[1].values()))) but obviously it didnt work.
You have a focus problem in your design: you claim that you're sorting only one dict, but your desired output sorts all three: my_dict, my_dict['A'] and my_dict['B']. You have to call sorted on both levels:
{letter: {contest: score
for contest, score in
sorted(sub_dict.items(), key=lambda val: val[1], reverse=True)
} for letter, sub_dict in sorted(my_dict.items(), key=lambda val: val[0])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With