我必须使用Python将这个input.json代码转换为输出响应。 我在python 3中创建输出字典时遇到问题。 请帮助我,我是python的新手。预先感谢。
Input.json
{
"function":"sample-text-function",
"questions":[
{
"instruction":"Hello! I'm Elth. I'm your personal assistant."
},
{
"text":"Before starting please tell me your first name",
"var":"first_name"
},
{
"text":"Please tell me your last name",
"var":"last_name"
},
{
"text":"And your gender?",
"options":[
"Male",
"female"
],
"var":"gender"
},
{
"text":"May I know your age?",
"var":"age"
},
{
"conditions":[
[
"age.isdigit() == False"
]
],
"text":"I couldn't quite get how that response can be your age :/ Please enter your valid age.",
"var":"age"
},
{
"instruction":"Congratulations! Registration Successful."
}
]
}
Output.json
{
"stage1": {
"Bot Says": [
{
"message": {
"text": "Hello! I'm Elth. I'm your personal assistant."
}
},
{
"message": {
"text": "Before starting please tell me your first name"
}
}
],
"User Says": "Srinath"
},
"stage2": {
"Bot Says": [
{
"message": {
"text": "Before starting please tell me your last name"
}
}
],
"User Says": "Akula",
},
"stage3": {
"Bot Says": [
{
"message": {
"text": "And your gender?",
"quick_replies": [
{
"content_type": "text",
"title": "Male",
"payload": "male"
},
{
"content_type": "text",
"title": "Female",
"payload": "female"
}
]
}
}
],
"User Says": "Male"
},
"stage4": {
"Bot Says": [
{
"message": {
"text": "May I know your age?"
}
}
],
"User Says": "what's your age?"
},
"stage5": {
"Bot Says": [
{
"message": {
"text": "I couldn't quite get how that response can be your age :/
Please enter your valid age."
}
}
],
"User Says": "31 yrs"
},
"stage6": {
"Bot Says": [
{
"message": {
"text": "Congratulations! Registration Successful."
}
}
]
}
}
到目前为止我的代码
例如,我只是试图在输出字典中插入一个值,并且出现错误
import json
from pprint import pprint
from collection import
with open('assignment_1_input_1.json') as f:
data=json.load(f)
output=dict(dict(list(dict(dict()))))
output['stage1']['Bot Says'][0]['message']['text']=data['questions'][0]['instruction']
print(output)
我得到的错误
line 11, in <module>
output['stage1']['Bot Says'][0]['message']['text']=data['questions'][0]['instruction']
KeyError: 'stage1'
答案 0 :(得分:0)
此行:
output=dict(dict(list(dict(dict()))))
实际上只是创建一个没有任何子字段的空字典,等效于
output = {}
您必须先声明每个子字段,然后再进行深入研究。实际上,
output['stage1'] = {}
有效,而:
output['stage1']['Bot Says'] = {}
没有。
我建议您使用所需的键初始化dict和每个子对象,例如:
output = {}
quick_reply = {'content_type': None, 'title': None, 'payload': None}
message = {'quick_replies': [], 'text': None}
bot_says = {'message': message}
user_says = {'User Says': None}
n_stages = 4
for n in range(1, n_stages):
stage_name = 'stage' + str(n)
output[stage_name] = {'Bot says': [bot_says], 'User Says': None}}
然后根据需要填写。
输出:
{'stage1': {'Bot Says': [{'message': {'quick_replies': [], 'text': None}}], 'User Says': None},
'stage2': {'Bot Says': [{'message': {'quick_replies': [], 'text': None}}], 'User Says': None},
'stage3': {'Bot Says': [{'message': {'quick_replies': [], 'text': None}}], 'User Says': None}}