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" : [
{ "id" : 1,
"name" : "xyz",
"nested_list" : [{"id" : "5","key":"val"},{"id" : "4","key":"val"}]
},
{
"outer_id" : 11,
"name" : "abc",
"nested_list" : [{"id" : "12","key":"val"},{"id" : "8","key" : "val"}]
}
]
}
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.