[英]Transforming List of dicts to nested list of dicts
我有一个这样的基础数据,在d_id中的数据库中有唯一的ID。 (数据命名为“输入”)
[
{
"d_id": "a1",
"d_name": "Fishing",
"location": "ABC",
"location_id": 1,
"rest_id": 2,
"rest_name": "Grilling"
},
{
"d_id": "a2",
"d_name": "catching",
"location": "ABC",
"location_id": 1,
"rest_id": 3,
"rest_name": "Kayaking"
},
{
"d_id": "a3",
"d_name": "Fishing2",
"location": "ABC",
"location_id": 1,
"rest_id": 2,
"rest_name": "Grilling"
},
{
"d_id": "a4",
"d_name": "Watering",
"location": "DEF",
"location_id": 2,
"rest_id": 4,
"rest_name": "Careoff"
}
]
我想按以下方式制作字典,这是按location_id,rest_id和d_id分类的嵌套json:
地区将具有多个位置,每个位置将具有多个rest_id,并且每个其余部分将具有多个d_id
{
"localities" : [
{
"location": "ABC",
"location_id": 1,
"rest_details": [
{
"rest_id": 2,
"rest_name": "Grilling",
"d_details" : [
{
"d_id" : "a1",
"d_name" : "Fishing"
},
{
"d_id" : "a3",
"d_name" : "Fishing2"
}
]
},
{
"rest_id": 3,
"rest_name": "Kayaking",
"d_details" : [
{
"d_id" : "a2",
"d_name" : "catching"
}
]
}
]
},
{
"location" : "DEF",
"location_id": 2,
"rest_details": [
{
"rest_id" : 4,
"rest_name" : "Careoff",
"d_details" : [
{
"d_id" : "a4",
"d_name": "Watering"
}
]
}
]
}
]
}
在过去的几天中,我尝试了以下操作,其中尝试将数据分为location_info,rest_info和d_info:
location_info = []
location_fields = {'location', 'location_id', 'd_id', 'rest_id' }
for item in input:
loc = {key:value for key,value in item.items() if key in location_fields}
location_info.append(loc)
k=1
while k<len(location_info):
if location_info[k] == location_info[k-1]:
location_info.pop(k-1)
else:
k = k+1
rest_info = []
rest_fields = {'rest_name','rest_id', 'd_id', 'loc_id'}
for item in input:
res = {key:value for key,value in item.items() if key in restaurant_fields}
restaurant_info.append(res)
d_info = []
d_fields = {'d_id', 'd_name', 'location_id'}
for item in input:
dis = {key:value for key,value in item.items() if key in d_fields}
d_info.append(dis)
for ta in location_info:
for tb in rest_info:
if ta['loc_id'] == tb['loc_id']:
ta['localities'] = tb
tb不会产生预期结果的第一回合。
您的代码充满错误。 您至少应该自己运行每个代码片段,并查看它们是否给出了所需的步骤输出(因为它们没有提供)。
除此之外,您的方法似乎不必要地复杂。 我会这样尝试:
locations = {}
for elem in input:
rest_details = []
curr_rest_detail = {"rest_id": elem["rest_id"], "rest_name":elem["rest_name"], "d_details":[{"d_id":elem["d_id"], "d_name":elem["d_name"]}]}
try:
rest_details = locations[elem["location_id"]]["rest_details"]
rest_detail_exists = False
for detail in rest_details:
if detail["rest_id"] == curr_rest_detail["rest_id"]:
rest_detail_exists = True
detail["d_details"].append({"d_id":elem["d_id"], "d_name":elem["d_name"]})
break
if not rest_detail_exists:
rest_details.append(curr_rest_detail)
except KeyError:
locations[elem["location_id"]] = {"location": elem["location"], "location_id":elem["location_id"], "rest_details":[curr_rest_detail]}
result = {"localities": [value for value in locations.values()]}
这段代码基本上会迭代您输入的元素,并在尚不存在任何条目时添加一个条目。 如果已经存在,则仅附加其他信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.