简体   繁体   English

如何在 python 中的字典列表 append 列表?

[英]How to append list of dictionary in python?

I have to update the JSON by appending another list named "Stage3" under "Stage2" in python.我必须通过在 python 的“Stage2”下附加另一个名为“Stage3”的列表来更新 JSON。

Initially, the JSON format is:最初,JSON 格式为:

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

After adding "Stage3".How I want is: Expected JSON Format:添加“Stage3”后。我想要的是:预期的 JSON 格式:

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

Python Python

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

How to append "Stage3" data inside this JSON?如何在此 JSON 中获取 append “Stage3”数据?

Thanks in advance提前致谢

You can do this:你可以这样做:

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

where mydict have assigned dictionary value. mydict 已分配字典值的位置。

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

Try this尝试这个

import json

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

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

Output: Output:

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

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

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