我有一个复杂的字典:
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
我想排序键名和nested_list [id]和预期输出:
[{'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'}]
我的尝试:
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)
它正确地对名称进行排序,接下来如果我按照相同的程序对nested_list [id]的“newlist”进行排序,它就不起作用了.
解决方法:
对所有嵌套列表进行排序,然后对顶级列表进行排序.您可以按任何顺序执行这些操作.对于键,我更喜欢使用lambdas而不是operator.itemgetter,因为我们需要将其中一个事物的结果转换为int(我假设,基于您的预期输出),并且您必须包装运算符无论如何,在lambda中的.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}]
标签:python,sorting,dictionary,python-2-7,list
来源: https://codeday.me/bug/20190623/1270953.html