繁体   English   中英

从 Python 中的字典列表创建多索引嵌套 json 或字典

[英]Created multi index nested json or dictionary from list of dictionaries in Python

我有以下字典列表:

"owners_data": [
{
  "owner_id":1,
  "in_hours": 30,
  "us_hours": 1,
  "client_id": "139",
  "in_revenue": 0,
  "in_te_cost": 0,
  "project_id": "100336",
},
{
  "owner_id":1,
  "in_hours": 30,
  "us_hours": 1,
  "client_id": "139",
  "in_revenue": 0,
  "in_te_cost": 0,
  "project_id": "100337",
},
{
  "owner_id":1,
  "in_hours": 30,
  "us_hours": 1,
  "client_id": "139",
  "in_revenue": 0,
  "in_te_cost": 0,
  "project_id": "100338",
},
{
  "owner_id":2,
  "in_hours": 30,
  "us_hours": 1,
  "client_id": "129",
  "in_revenue": 0,
  "in_te_cost": 0,
  "project_id": "100339",
},
{
  "owner_id":2,
  "in_hours": 30,
  "us_hours": 1,
  "client_id": "149",
  "in_revenue": 0,
  "in_te_cost": 0,
  "project_id": "100343",
}

现在我需要将其转换为嵌套的 JSON 或字典,以便将值分组在相应的所有者、客户和项目下。 所以 output 看起来像

  "owners_data": {
    "1":{
       "139":{
            "100336":{
               "in_hours": 30,
               "us_hours": 1,
               "in_revenue": 0,
               "in_te_cost": 0,,
            },
            "100337":
            {
                "in_hours": 32,
                "us_hours": 1,
                "in_revenue": 100,
                "in_te_cost": 192,
            },
            "100338":
            {
                "in_hours": 30,
                "us_hours": 1,
                "in_revenue": 1000,
                "in_te_cost": 33,
            }
       }
    },
    {
    "2" {
        "100339":{
            "in_hours": 30,
            "us_hours": 1,
            "in_revenue": 1000,
            "in_te_cost": 33,
        },
        "100343":{
            "in_hours": 30,
            "us_hours": 1,
            "in_revenue": 1000,
           "in_te_cost": 33,
        }
    }
    }
    }

以上不是正确的 JSON,但我需要以正确的格式使用索引作为相应的字段。 这个怎么做?

我正在尝试以下操作:

output = defaultdict(dict)
for data in acc_owner_data:
    output[int(data['acc_owner_id'])][int(data['client_id'])] = data
print(dict(output))
exit()

但这只是为客户显示一个项目,即使有多个项目。 如果我尝试在那里添加 projec_id,例如output[int(data['acc_owner_id'])][int(data['client_id'])][int(data['project_id'])]它显示KeyError: 139

如何解决这个问题?

我想你可以使用嵌套的defaultdict来修复它:

import collections

def tree():
    return collections.defaultdict(tree)


root = tree()
for obj in adict['owners_data']:
    owner_id = obj.pop('owner_id')
    client_id = obj.pop('client_id')
    project_id = obj.pop('project_id')
    root[owner_id][client_id][project_id] = obj

import json

print(json.dumps(root))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM