我正在尝试对字典列表和列表的多个参数进行排序。我检查了 How do I sort a list of dictionaries by values of the dictionary in Python? .
我有一个复杂的字典:
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
我想对键 name
和 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]
的“新列表”进行排序,它就不起作用了。
最佳答案
对所有嵌套列表进行排序,然后对顶级列表进行排序。您可以按任一顺序执行这些操作。对于键,我更喜欢在这里使用 lambda 而不是 operator.itemgetter
,因为我们需要将其中一个事物的结果转换为 int(我假设,基于您的预期输出),并且您无论如何都必须将 operator.itemgetter
包装在 lambda 中才能做到这一点。
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 - 对字典/列表列表中的多个参数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34425055/