Another way of doing it would be to utilize csv
module. (Note that in your dictionary you have an upper case C
which I corrected in my code below):
import csv
lookup = {'ge60le90': 'confidence<90','gt90': 'confidence>90', 'lt60': 'confidence<60'}
count = {'lt60': {'a': 0, 'b': 0, 'c': 0, 'd': 0}, 'ge60le90': {'a': 4, 'b': 0, 'c': 0, 'd': 0}, 'gt90': {'a': 0, 'b': 1, 'c': 2, 'd': 1} }
# Getting keys from dictionary that match them with titles below.
rowKeys = [k for k in count['lt60'].keys()]
titles = [['relation type'] + list(lookup[k] for k in count.keys())]
# Getting all row variable values for every title.
rows = [[count[k][i] for k in count.keys()] for i in rowKeys]
# Concatenating variables and values.
fields = [[rowKeys[i]] + rows[i] for i in range(len(rowKeys))]
# Concatenating final output to be written to file.
result = titles + fields
print("Final result to be written: ")
for r in result:
print(r)
# Writing to file.
with open("output.csv", "w", newline="") as outFile:
writer = csv.writer(outFile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerows(result)
Note that the ;
delimiter works for European Windows and might not work for you. In this case, use ,
instead.