Sort by several parameters in the list of dictionaries / lists

I am trying to sort by several parameters a list of dictionaries and lists. I checked How to sort a list of dictionaries by dictionary values ​​in Python? .

I have a complex dictionary:

dict1 = 
{"outer_list" : [ 
#1st dict
{ "id" : 1,
"name" : "xyz",
"nested_list" : [{"id" : "5","key":"val"},{"id" : "4","key":"val"}]
},  

#2nd dict
{ 
"outer_id" : 11,
"name" : "abc",
"nested_list" : [{"id" : "12","key":"val"},{"id" : "8","key" : "val"}]
}
]  # outer_list ends
}  #dict1 ends

I want to sort by key nameand nested_list[id]and the expected result:

 [{'outer_id': 11, 'name': 'abc', 'nested_list': [{'id': '8', 'key': 'val'}, {'id': '12', 'key': 'val'}]}, {'nested_list': [{'id': 4, 'key': 'val'}, {'id': 5, 'key': 'val'}], 'id': 1, 'name': 'xyz'}]  

My attempt:

def sort_cluster(data):
    for items in data:
        item=items['outer_list']
        newlist = sorted(item, key=itemgetter('name'))
    print newlist


if __name__ == "__main__":
    list1=[]
    list1.append(dict1)
    sort_cluster(list1)

It is sorted by name correctly, then if I follow the same procedure to sort by "newlist" for nested_list[id], it does not work.

+4
source share
1 answer

nested_lists, . . lambdas operator.itemgetter , int ( , ), operator.itemgetter .

def do_thing(dct):
    lst = dct["outer_list"]

    # Sort the nested_lists, assuming you want to sort by the numeric value of the "id" value
    for obj in lst:
        obj["nested_list"].sort(key=lambda d: int(d["id"]))

    # Sort the outer_list
    lst.sort(key=lambda d: d["name"])

    return lst

:

>>> do_thing(dict1)
[{'name': 'abc', 'outer_id': 11, 'nested_list': [{'key': 'val', 'id': '8'}, {'key': 'val', 'id': '12'}]}, 
 {'name': 'xyz', 'nested_list': [{'key': 'val', 'id': '4'}, {'key': 'val', 'id': '5'}], 'id': 1}]
+4

Source: https://habr.com/ru/post/1621344/


All Articles