簡體   English   中英

將字典列表轉換為嵌套字典列表

[英]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)

用於唯一的location_info條目

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_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_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)

用於將rest_info與location_info合並

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM