【问题标题】:How to append list of dictonary to dictionary in python?如何将字典列表附加到python中的字典?
【发布时间】:2020-12-06 08:53:42
【问题描述】:

如何在python中追加字典列表?

我正在尝试使用从 MongoDB 检索数据的 python 创建 JSON 数据。 我需要获取以下格式的 JSON 数据。 注意:我从 db 中检索了所有必需的数据。我不确定是否以所需的 JSON 格式附加该数据。

JSON 数据:

"System_Details":
{
"System_id":"001",
"Details":[
{
  "name":"Job-Info"
  "job":[
  {
    "category":"1",
    { 
      "eid":"01",
      "role":"associate-1"
    },
    {
      "eid":"02",
      "role":"associate-2"
    },
    { 
      "eid";"03",
      "role":"associate-3"
    }
  },

  {
    "category":"2",
    { 
      "eid":"04",
      "role":"associate-4"
    },
    {
      "eid":"05",
      "role":"associate-5"
    },
    { 
      "eid";"06",
      "role":"associate-6"
    }
  },
   
]
}
]}

我的脚本:

System_Details = {}
System_Details['Details'] = []
job = []
job_dict = {}
System_Details["System_id"]= <SYSTEMID ## which is retrieved from db>
job.append(job_dict)   #job_dict is having above json values which is mentioned inside job list("job":[])

现在工作 = [ ] 包含

  "job":[
  {
    "category":"1",
    { 
      "eid":"01",
      "role":"associate-1"
    },
    {
      "eid':"02",
      "role":"associate-2"
    },
    { 
      "eid";"03",
      "role":"associate-3"
    }
  },

  {
    "category":"2",
    { 
      "eid":"04",
      "role":"associate-4"
    },
    {
      "eid':"05",
      "role":"associate-5"
    },
    { 
      "eid";"06",
      "role":"associate-6"
    }
  },
]

如何将此列表附加到 System_Details['Details']?

追加时请注意 System_Details ['Details'] 中的花括号。

简而言之

"System_Details":
{
  "Details":[
    { 
      ...
      ...
       "job":[
         {
           ...
         },
         {
           ...
         }
      ]
   }
]}

如何将 "job":[] 附加到 "Details":[] 中?

提前致谢。

【问题讨论】:

  • 你的问题不清楚
  • 你发布的json无效

标签: python json list dictionary append


【解决方案1】:

由于问题不清楚,请根据给定的理解回答。

"System_Details":
{
  "Details":[
    { 
      ...
      ...
       "job":[
         {
           ...
         },
         {
           ...
         }
      ]
   }
]
}

所以,有两个列表 Detailsjob。您希望将 job 中存在的所有项目附加到 Details 列表中。

您可以在 python 中使用extend() 将一个列表附加到另一个列表。

>>> l = [1, 2]
>>> l.extend([3, 4])
>>> l
[1, 2, 3, 4]
>>> l.extend('foo')
>>> l
[1, 2, 3, 4, 'f', 'o', 'o']
>>> l.extend((5, 6))
>>> l
[1, 2, 3, 4, 'f', 'o', 'o', 5, 6]
>>> l.extend({'x': 100, 'y': 200})
>>> l
[1, 2, 3, 4, 'f', 'o', 'o', 5, 6, 'y', 'x']

如果回答了您的问题,请更新您的问题或对答案发表评论。

【讨论】:

    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 2023-02-02
    • 2013-03-27
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多