Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a nested dictionary in Python 2 times?

Tags:

python

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.

like image 467
gpavlov Avatar asked Nov 27 '25 11:11

gpavlov


1 Answers

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])
}
like image 174
Prune Avatar answered Nov 30 '25 01:11

Prune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!