将dicts列表转换为嵌套的dicts列表

时间:2015-07-05 05:21:46

标签: python json dictionary

我有这样的基础数据,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

for 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不会产生预期结果的第一段。

1 个答案:

答案 0 :(得分:0)

您的代码中存在错误。您至少应该自己运行每个片段,看看他们是否提供了所需的步骤输出(因为他们不会)。

除此之外,您的方法似乎不必要地复杂化。我会这样试试:

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()]}

此代码基本上遍历输入的元素,并在条目尚不存在时添加条目。如果它已经存在,则只附加附加信息。