[Django]-Sort list of dictionaries based on nested keys

5πŸ‘

βœ…

In order to sort list of dictionary with nested keys, you may use lambda expression as:

my_dict_list = [{'parent_key': {'my_key_1': 10, 'my_key_2': 2}},
                {'parent_key': {'my_key_1': 5, 'my_key_2': 4}},
                {'parent_key': {'my_key_1': 10, 'my_key_2': 6}},
                {'parent_key': {'my_key_1': 5, 'my_key_2': 2}},
                {'parent_key': {'my_key_1': 10, 'my_key_2': 3}},
]

sorted(my_dict_list, key=lambda x: (
        x['parent_key']['my_key_1'], x['parent_key']['my_key_2']))
#  value of first 'key' to sort-^                     ^
#               in case of same value for first 'key'-^   
#               sort based on second key -------------^

which returns the sorted list as:

[{'parent_key': {'my_key_2': 2, 'my_key_1': 5}}, 
 {'parent_key': {'my_key_2': 4, 'my_key_1': 5}}, 
 {'parent_key': {'my_key_2': 2, 'my_key_1': 10}}, 
 {'parent_key': {'my_key_2': 3, 'my_key_1': 10}}, 
 {'parent_key': {'my_key_2': 6, 'my_key_1': 10}}]

Leave a comment