1

我有这个代码:

#//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 循环转换为字典?但我可能是错的...

关于如何最简单地做到这一点的任何想法?

编辑:
使用您的建议:

    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)

我没有得到我所期望
的我得到列表 n 的 4 行。没有指示 DICT 中的值。我究竟做错了什么...

4

1 回答 1

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 中,则打印“不可用”字样。

编辑2

您太努力了 - 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)
于 2013-06-24T06:24:48.540 回答