This is my dictionary format:
quest_attr = {
"questions": [
{
"Tags": [
{
"tagname": ""
}
],
"Title": "",
"Authors": [
{
"name": ""
}
],
"Answers": [
{
"ans": ""
}
],
"Related_Questions": [
{
"quest": ""
}
]
}
]
}
I want to add list of "Tags"
such that the result will be:
"questions":[
{
"Tags": [
{"tagname":"#Education"}, {"tagname":"#Social"}
],
remaining fields...
}
The remaining fields can be assumed to be null. And I want to add multiple questions to the main "questions"
list.
I am using this code but he results are not as expected.
ind=0
size=len(tags)
while ind<size:
quest_attr["questions"].append({["Tags"].append({"tagname":tags[ind]})})
ind=ind 1
And if I maintain a variable for looping through the list of questions like:
quest_attr["questions"][ind]["Tags"].append({"tagname":tags[ind]
It gives an error that the index is out of range. What should I do?
CodePudding user response:
It appears that the index variable ind
is intended to iterate only through the list of tags. The way you have the append structured, your loop will attempt to attach the next tag to the next question in the questions list, instead of adding the rest of the tags to the same question.
If you were to add the same set to multiple questions, you need loop through the questions list separately while nesting your append statement for the tags inside another loop. On the other hand, if there's only one question you want to target, just use the index number, [0]
in this case.
Something like this would perhaps work better but more context would help:
for question in quest_attr["questions"]:
for tag in tags:
question["Tags"].append({"tagname":tag})
CodePudding user response:
Please don't make a mess with dict and list like your code. Here I recommend a simpler deploy.
quest_attr = {
'questions': {
"Tags":[],
"Title":"",
"Authors":[],
"Answers":[],
"Related_Questions":[]
}
}
tags = [ {"tagname":"#Education"},{"tagname":"#Social"} ]
quest_attr["questions"]['Tags'] = tags
print(quest_attr)