如何排序嵌套字典列表?字典的实际列表为
[
{
"Name":"21_12",
"Details":[
{
"name":"Cat",
"Data":[
{
"status":"Passed",
"id":3,
"loop_count":1
},
{
"status":"Passed",
"id":5,
"loop_count":1
}
]
},
{
"name":"Dog",
"Data":[
{
"status":"Passed",
"id":1,
"loop_count":1
},
{
"status":"Passed",
"id":2,
"loop_count":1
}
]
}
]
}
]
,其中字典的内部列表应按"id"甚至在"数据"中也不例外。并在"详细信息">
所需输出:
[
{
"Name":"21_12",
"Details":[
{
"name":"Dog",
"Data":[
{
"status":"Passed",
"id":1,
"loop_count":1
},
{
"status":"Passed",
"id":2,
"loop_count":1
}
]
},
{
"name":"Cat",
"Data":[
{
"status":"Passed",
"id":3,
"loop_count":1
},
{
"status":"Passed",
"id":5,
"loop_count":1
}
]
}
]
}
]
已尝试排序的内置函数。
这应该可以完成工作:
def order_structure(structure):
for details in structure:
sorted_detail = sorted(details["Details"], key=lambda x: max(x["Data"], key= lambda y: y["id"])["id"])
details["Details"] = sorted_detail
for data in details["Details"]:
sorted_data = sorted(data["Data"], key= lambda x: x["id"])
data["Data"] = sorted_data
order_structure(structure)
如果你不想在原地排序,但想要生成一个有序的副本,只需在structure.copy()
上做同样的事情
def get_ordered_structure(structure):
structure_copy = structure.copy()
for details in structure_copy:
sorted_detail = sorted(details["Details"], key=lambda x: max(x["Data"], key= lambda y: y["id"])["id"])
details["Details"] = sorted_detail
for data in details["Details"]:
sorted_data = sorted(data["Data"], key= lambda x: x["id"])
data["Data"] = sorted_data
return structure_copy
ordered_structure = get_ordered_structure(structure)
这样,原来的结构不会改变
即使主列表中有多个元素,如果它们遵循相同的结构,该函数也可以工作。
您可以使用python pandas来解决这个问题。
myDictionary = [
{
"Name":"21_12",
"Details":[
{
"name":"Cat",
"Data":[
{
"status":"Passed",
"id":3,
"loop_count":1
},
{
"status":"Passed",
"id":5,
"loop_count":1
}
]
},
{
"name":"Dog",
"Data":[
{
"status":"Passed",
"id":1,
"loop_count":1
},
{
"status":"Passed",
"id":2,
"loop_count":1
}
]
}
]
}
]
import pandas as pd
for i in range(len(myDictionary[0]["Details"])):
df = pd.DataFrame(myDictionary[0]["Details"][i]["Data"])
df.sort_values("id", inplace=True)
myDictionary[0]["Details"][i]["Data"] = df.to_dict(orient="records")
print(myDictionary)
你可以使用python的排序函数和正确的键函数
sorted_list = sorted(list_of_dicts, key=lambda x: x['Details']['Data']['id'])