0

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!

Machavity
  • 30,841
  • 27
  • 92
  • 100
Poppel
  • 17
  • 4
  • 3
    use a `collections.OrderedDict` – Gsk Feb 27 '19 at 09:15
  • Or convert dict.keys() to a list, sort it and iterate over the sorted list. – f.wue Feb 27 '19 at 09:17
  • try printing the dictionary, you will notice every time you print it, it is different, same is the case when you are writing to a csv file. you can use what @Gsk has mentioned – Rahil Hastu Feb 27 '19 at 09:20
  • Use `csv.DictWriter(..., fieldnames=[]` instead. The parameter `fieldnames=` defines the order of the columns. – stovfl Feb 27 '19 at 11:17

1 Answers1

0

A solution based on sorted keys (does not preserve the original structure of the data). Not sure if this is the one you are looking for.

import csv

data = {'key1': ['apple', 'kiwi'], 'other_key1': ['lemon', 'kiwi'],
        'key2': ['haha', 'lol'], 'key233': ['meat'],
        'key3': ['meat']}

with open('out.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=',')
    for key in sorted(data.keys()):
        for value in data[key]:
            writer.writerow([key, value])
balderman
  • 22,927
  • 7
  • 34
  • 52