0

Existing Json data

{'list': {'KEY1': 'One'}}

Need to add

{'KEY2': 'Two'}

Result :

{'list': {'KEY1': 'One', 'KEY2': 'Two'}}

Any idea how to do it in python?

I'm tried append but it creates array in json object like this

{'list': [{'KEY1': 'One'}, {'KEY2': 'Two'}]}
4
  • {'list': {'KEY1': 'One'}, {'KEY2': 'Two'}} is invalid syntax. {'list': [{'KEY1': 'One'}, {'KEY2': 'Two'}]} is probably the closest to what you are looking for. Commented Mar 6, 2018 at 4:22
  • Or you want {'list': {'KEY1': 'One', 'KEY2': 'Two'}}? Commented Mar 6, 2018 at 4:28
  • Oops.., Modified. Yes exactly I wanted like this Commented Mar 6, 2018 at 4:36
  • @jignasha {'list': {'KEY1': 'One', 'KEY2': 'Two'}} is valid Commented Mar 6, 2018 at 4:39

1 Answer 1

4

You can use dict.update:

s = {'list': {'KEY1': 'One'}}
d = {'KEY2': 'Two'}
s['list'].update(d)

Output:

{'list': {'KEY1': 'One', 'KEY2': 'Two'}}

Or in Python3, you can use dictionary unpacking:

s = {'list': {'KEY1': 'One'}}
d = {'KEY2': 'Two'}
s = {'list':{**s['list'], **d}}

Output:

{'list': {'KEY1': 'One', 'KEY2': 'Two'}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.