写入.csv多个列

时间:2013-06-24 05:59:23

标签: python csv for-loop dictionary writer

我有这段代码:

#//Running my argument to check if the item in list is in dictionary and returning    this + corresponding value in dictionary//#
for key in n:
    if DICT.get(key):
        print ((key) + ' : ' + DICT[key])
    else:
        print((key) + ' : ' + "Not Available")

#Writing to .cvs file       
with open('test_write.csv', 'w') as fp:
    a = csv.writer(fp)
    a.writerows(n)

我希望将上述for循环中的结果写入.csv。
目前,我将代码的第一部分的每个字母分别列在单独的列中 我需要在每一列中都有两个..
我建议我需要将for循环转换为dict?但我可能错了......

关于如何做到最简单的任何想法?

编辑:
使用你的消化:

    with open('test_write.csv', 'w') as fp:
        a = csv.writer(fp)
        for key in n:
        if DICT.get(key):
            print ((key) + ' : ' + DICT[key])
            a.writerow(n)
        else:
            print((key) + ' : ' + "Not Available")
            a.writerow(DICT.get(n,"Not Available") for name in n)

我没有得到我期待的东西 我得到了4行我的列表n。 没有任何关于DICT价值的迹象。 我做错了什么......

1 个答案:

答案 0 :(得分:2)

writerows获取可迭代列表。尝试使用writerow。从事物的外观来看,n是一个字典,所以要获得一行标题和一行值,请执行:

a.writerow(n.keys())
a.writerow(n.values())

可以为第一行写a.writerow(n),但我更愿意更明确地说明这一点。

添加所有默认值的快捷方式:

names = ['list','of','all','expected','keys']
data = {'list':'A', 'of':'zoo', 'keys':'foo'}
default = dict.fromkeys(names,"Not Available")
default.update(data)
data = default

保留内容数据:

{'all': 'Not Available', 'of': 'zoo', 'list': 'A', 'expected': 'Not Available', 'keys': 'foo'}

修改

鉴于DICT = {1:a,2:b,3:c,4:d}且列表n = [1,2,5,6],只需执行:

a.writerow(n)
a.writerow(DICT.get(name,"Not Available") for name in n)

将在您的CSV文件中打印两行,一行的密钥名称为n,另一行的值为DICT,如果特定的密钥不在DICT中,则为“不可用”。

<强> EDIT2

你太努力了--DICT.get将负责是否存在一个条目:

with open('test_write.csv', 'w') as fp:
    a = csv.writer(fp)
    a.writerow(n)
    a.writerow(DICT.get(name,"Not Available") for name in n)

这是相同的代码,有一些更详细的形式:

with open('test_write.csv', 'w') as fp:
    a = csv.writer(fp)
    # write row of header names
    a.writerow(n)

    # build up a list of the values in DICT corresponding to the keys in n
    values = []
    for name in n:
        if name in DICT:
            values.append(DICT[name])
        else:
            values.append("Not Available")
    # or written as a list comprehension:
    # values = [DICT[name] if name in DICT else "Not Available" for name in n]
    # 
    # or just use DICT.get, which does the name checking for us, and chooses the 
    # default value if the key is not found
    # values = [DICT.get(name, "Not Available") for name in n]

    # now write them out
    a.writerow(values)

    # or finally, the list build and writerow call all in one line
    # a.writerow(DICT.get(name,"Not Available") for name in n)

修改

    # to write out the transpose of the previous lines (that is, instead of 
    # a line of names and a line of the matching values, a line for each
    # name-value pair), use Python's zip builtin:
    for nameValueTuple in zip(n,values):
        a.writerow(nameValueTuple)