【问题标题】:How to append list of dictionary in python?如何在python中附加字典列表?
【发布时间】:2020-12-06 11:14:07
【问题描述】:

我必须通过在 python 中的“Stage2”下附加另一个名为“Stage3”的列表来更新 JSON。

最初,JSON 格式为:

"Stage1":{
   "Stage2":[
     {
        ...
     }
  ]
}

添加“Stage3”后。我想要的是: 预期的 JSON 格式:

"Stage1":{
   "Stage2":[
     {
        ...
      "Stage3":[
         {
             ...
         },
          {
             ...
          }
        ]
     }
  ]
}

Python

Stage1 = {}
Stage1['Stage2'] = []
Stage3 = [#<Where i'm having some dicitionary value>#]

如何在这个 JSON 中附加“Stage3”数据?

提前致谢

【问题讨论】:

  • 目前Stage2 是一个列表,因此您不能在此处附加带有键的项目。除非您想将其添加到该列表中的第一个元素

标签: python json list dictionary append


【解决方案1】:

试试这个

import json

Stage1 = {}
Stage1['Stage2'] = [{}]
Stage3 = [{'a': 1}, {'b': 2}]
Stage1['Stage2'][0]['Stage3'] = Stage3

res = {'Stage1': Stage1}
print(json.dumps(res))

输出:

{
  "Stage1": {
    "Stage2": [
      {
        "Stage3": [
          {
            "a": 1
          },
          {
            "b": 2
          }
        ]
      }
    ]
  }
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    mydict['Stage1']['Stage2'].append({"Stage3":"valueof3"})
    

    mydict 在哪里分配了字典值。

    检查这个: https://repl.it/repls/CourteousGreenDownloads

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 2020-01-28
      • 2021-11-26
      • 2020-10-14
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      相关资源
      最近更新 更多