aveleon
aveleon

Reputation: 167

Write dictionary (keys and values) to a csv file

I just want the csv file to look like this:

key,item1,item2,item3 key2,itema,itemB,itemC

and so on

The dictionary has a key and the value is a list of floats. This is the current code I have to write to the csv file but all it does is write out the key like this: k,e,y,s

Any help is appreciated

with open(outFileName1, 'w') as outfile:
   csv_Writer = csv.writer(outfile)
   csv_Writer.writerows(dict1)

Upvotes: 5

Views: 10510

Answers (3)

Rob Cowie
Rob Cowie

Reputation: 22619

Your current code iterates the dictionary which yields keys only. Take a look at

import csv

data = {
    'key1': ['item1', 'item2'],
    'key2': ['item3', 'item4']
}

with open('', 'w') as outfile:
    writer = csv.writer(outfile)
    for k, v in data.iteritems():
        writer.writerow([k] + v)

Notice that it iterates key-value pairs returned by .iteritems(). The key is inserted into a list which is concatenated with the value list.

Upvotes: 1

MA1
MA1

Reputation: 2847

import csv


dict_data = {'key1': [1, 2, 3], 'key2': [4, 5, 6]}

with open("dict2csv.txt", 'w') as outfile:
   csv_writer = csv.writer(outfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

   for k,v in dict_data.items():
       csv_writer.writerow([k] + v)

This code will write each key, value pair in your desire format on separate line in csv file.

Upvotes: 3

Maciek
Maciek

Reputation: 792

Without getting into details how CSV works you can easily solve it with something like:

with open("out.txt", 'w') as outfile:
    for k,v in dict1.items():
        outfile.write(str(k))
        for item in v:
            outfile.write(","+str(item))
        outfile.write(" ")

Upvotes: 1

Related Questions