简体   繁体   中英

Unpacking list items from a dictionary & writing to a CSV file

I have a dictionary which contains a list of 4 items per key.
I'm trying to write each individual list item to a Var column in a CSV file, but I haven't been having much luck.

try:
    f = open('numbers2.csv', 'wt')
    writer = csv.writer(f, lineterminator = '\n')
    writer.writerow(('Var1', "Var2", 'Var3', "Var4",))
    for x in exchangeDict2.iteritems():
        writer.writerow(x)

This code will print the key in one column, and the list in the other.

Looks like you need to iterate over dictionary values, use itervalues() :

for value in exchangeDict2.itervalues():
    writer.writerow(value)

Also, use with context manager while working with files (it handles close() for you):

with open('numbers2.csv', 'wt') as f:
    writer = csv.writer(f, lineterminator = '\n')
    writer.writerow(('Var1', "Var2", 'Var3', "Var4",))
    for value in exchangeDict2.itervalues():
        writer.writerow(value)

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