简体   繁体   中英

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)
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.

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(" ")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM