简体   繁体   中英

how to write a dictionary with one key multiple values to a csv file

I have a dictionary of the following form

>>> {'1' : [V3210 , 234567 ,1235675 , 23], '2' : [v3214 , 5678 ,65879 ,89} , ...}

how to write this dictionary to a csv file??

thanks

Use the builtin csv module. This is assuming you want it in a key,value1,value2,... format.

import csv

with open('filename', 'w') as f:
    c = csv.writer(f)

    for key, value in d.items():
        c.writerow([key] + value)

Assuming the numeric keys are line numbers, try something like this:

theDict = {'1' : [V3210 , 234567 ,1235675 , 23], '2' : [v3214 , 5678 ,65879 ,89] }
largestkey=max(map(int,theDict.keys()))
with file("out.csv") as f:
    for linenum in range(largestkey+1):
        f.write(",".join(theDict[str(linenum)])
        f.write("\n")

You'll want to look at Python's string API, list handling, and file handling to get more familiar with Python...

Using Python's csv module would make doing this super simple:

import csv

d = {'1' : ['V3210', 234567, 1235675, 23], '2' : ['v3214', 5678, 65879 ,89], }

with open('output.csv', 'wb') as csvfile:
    csv.writer(csvfile).writerows([row[0]] + row[1] for row in d.iteritems())

Note the iteritems() dictionary method is gone in Python 3, so you'd need to use d.items() instead.

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