How to sort a nested dictionary in Python 2 times?

Viewed 95

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.

2 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])
}

You can use nested dict comprehension on the sorted key/value pairs :

d = {k: {k2: v for k2, v in sorted(dic.items(), key=lambda x: x[1], reverse=True)} for k, dic in sorted(my_dict.items(), key=lambda x: x[0])}

Looks a bit ugly but it does the job

Related