1

Desired output:

{"MainKey": 
   [{"key01":"value01","key02":"value02"},
    {"key11":"value11","key22":"value02"}
   ]
}

The code I tried:

data = {}
data2=[{}]

data2[0]['key01'] = 'value01'
data2[0]['key02']=  'value02'

data2[1]['key11'] = 'value11'  #index out of bounds error
data2[1]['key12']=  'value12'

data['MainKey']=data2

import json 
with open('try.json", 'w') as outfile:
 json.dump(data,outfile)

But this gives index out of bounds error for the second set of values in data2. How do i solve this?

2
  • 1
    You are getting the error because you only have one dict in data2 try: data2=[{}, {}] Commented Jun 18, 2018 at 10:07
  • @Rakesh How would i make an array with n number of such items though? Commented Jun 18, 2018 at 10:10

2 Answers 2

2

One approach is to create the number of dict using range.

Ex:

data = {}

data2 = [{} for i in range(2)]

data2[0]['key01'] = 'value01'
data2[0]['key02']=  'value02'

data2[1]['key11'] = 'value11'
data2[1]['key12']=  'value12'

data['MainKey']=data2
print(data)

Output:

{'MainKey': [{'key01': 'value01', 'key02': 'value02'}, {'key12': 'value12', 'key11': 'value11'}]}
Sign up to request clarification or add additional context in comments.

1 Comment

Please accept ans if it solved your problem. Thanks.
0

data2 is a list with only one item, so its index cannot be greater than 0.

>>> data2=[{}]
>>> data2[0]['key01'] = 'value01'
>>> data2[0]['key02'] = 'value02'
>>> data2

[{'key01': 'value01', 'key02': 'value02'}]

2 Comments

I figured, but how do i solve this and make an array with n number of {} items in data2?
data2 = [{} for i in range(n)]

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.