I have 2 lists from these two lists i have to place values in multiple rows data is json file in which these values need to be placed listA = [A,B,C,D] listB = [11,12,13,14]
Result I would like to see as in json file as
"A" : [{
section = 11
}],
"B" : [{
section = 12
}]'
"C" : [{
section = 13
}]
"D" : [{
section = 14
}]
but currently i am getting as below
"A" : [{
section = 14
}],
"B" : [{
section = 14
}]'
"C" : [{
section = 14
}]
"D" : [{
section = 14
}]
The code i am using is below,here data is main json file where i need to place value
for j in listA:
for k in listB:
if j == 'A' :
data[j][0]["section"] = str(k)
elif j == 'B':
data[j][0]["section"] = str(k)
elif j == 'C' :
data[j][0]["section"] = str(k)
elif j == 'D' :
data[j][0]["section"] = str(k)
CodePudding user response:
I hope I've understood your question well. If you have data
in this format:
data = {
"A": [{"section": ""}],
"B": [{"section": ""}],
"C": [{"section": ""}],
"D": [{"section": ""}],
}
Then you can use zip()
to iterate over listA
and listB
simultaneously:
listA = ["A", "B", "C", "D"]
listB = [11, 12, 13, 14]
for a, b in zip(listA, listB):
data[a][0]["section"] = b
print(data)
Prints:
{
"A": [{"section": 11}],
"B": [{"section": 12}],
"C": [{"section": 13}],
"D": [{"section": 14}],
}