Pepper
Pepper

Reputation: 65

How to append list of dictionary in python?

I have to update the JSON by appending another list named "Stage3" under "Stage2" in python.

Initially, the JSON format is:

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

After adding "Stage3".How I want is: Expected JSON Format:

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

Python

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

How to append "Stage3" data inside this JSON?

Thanks in advance

Upvotes: 0

Views: 83

Answers (2)

Midha Tahir
Midha Tahir

Reputation: 138

You can do this:

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

where mydict have assigned dictionary value.

Check this: https://repl.it/repls/CourteousGreenDownloads

Upvotes: 1

deadshot
deadshot

Reputation: 9051

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:

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

Upvotes: 0

Related Questions