It's hard to tell without the actual input data, or the actual output, what's going on.
I mocked up some input data like this to satisfy for i in test_data["data"][1]:
test_data = {
"data": [
"foo",
["Y1", "i1", "i2", "i3"],
]
}
and for z in test_results:
test_results = ["Y2", "z1", "z2", "z3"]
Now, when I run your code as-is, I get an output CSV that looks like:
['Y1', 'i1', 'i2', 'i3'] ['Y2', 'z1', 'z2', 'z3']
(I assume your header isn't in the actual input, but I included it just to make your small example code work.)
Following @Tim Roberts' suggestion, using zip() is probably the most correct way to join your two columns:
rows = zip(test_data["data"][1], test_results)
print(list(rows))
and we can see that the values from data and results have been properly joined:
[
("Y1", "Y2"),
("i1", "z1"),
("i2", "z2"),
("i3", "z3"),
]
From here, using the csv writer is just a few lines of code:
with open("output.csv", "w", newline="") as f_out:
writer = csv.writer(f_out, delimiter="\t", lineterminator="\n")
writer.writerows(rows)
and I get:
Y1 Y2
i1 z1
i2 z2
i3 z3
To me, the most important concept to take away is get your data set up first (like we can see in that print(list(rows)) statement), then do the CSV writing stuff.
Here's the complete program:
import csv
test_data = {
"data": [
"foo",
["Y1", "i1", "i2", "i3"],
]
}
test_results = ["Y2", "z1", "z2", "z3"]
rows = zip(test_data["data"][1], test_results)
with open("output.csv", "w", newline="") as f_out:
writer = csv.writer(f_out, delimiter="\t", lineterminator="\n")
# writer.writerow(["Y1", "Y2"]) # if you need to write your header manually
writer.writerows(rows)
I also don't see a need to append: get your data composed and sorted, then just "write" to the CSV file, once.
test_data['data'][1]andtest_resultsthe same size? If so, you can just zip them. I'll show in an answer.