0

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.

4

1 回答 1

2

看起来您需要遍历字典值,使用itervalues()

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

此外,with在处理文件时使用上下文管理器(它close()为您处理):

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)
于 2013-09-13T19:35:08.593 回答