I'm trying to write dict to csv with first column filled with keys, second column filled with values, and only one key/value per row.
import csv
myDict = {'key1': ['apple', 'kiwi'], 'key2': ['haha','lol'], 'key3': ['meat']}
f= open('file.csv', 'w', newline='')
with open('file.csv', 'w', newline='') as f:
writer = csv.writer(f,delimiter=',')
for key, values in myDict.items():
for value in values:
writer.writerow([key, value])
The optimal output should be:
key1,apple
key1,kiwi
key2,haha
key2,lol
key3,meat
However when I run the code, it does not always write the keys and values in the order I desire, it writes the keys and values to the csv in a random manner.
(Background: the ordering of the keys and values is an output from previews coding)
Can you please point out what I missed here? Thanks in advance!
]` instead. The parameter `fieldnames=` defines the order of the columns.
– stovfl Feb 27 '19 at 11:17