【发布时间】:2018-11-27 03:43:04
【问题描述】:
期望的输出:
{"MainKey":
[{"key01":"value01","key02":"value02"},
{"key11":"value11","key22":"value02"}
]
}
我试过的代码:
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)
但这会导致 data2 中第二组值的索引超出范围错误。我该如何解决?
【问题讨论】:
-
您收到错误是因为
data2中只有一个字典尝试:data2=[{}, {}] -
@Rakesh 我将如何创建一个包含 n 个此类项目的数组?
标签: python arrays json python-3.x