基于字典值将单元格中的数据写入csv文件

2024-10-01 05:01:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试根据字典值将数据写入CSV列。 例如,我有一个For循环,它将在每个循环中生成一个字典

{JLKJ: 1}
{BNMM: 4}
{HUGF: 5}...

example

我的目标是尝试根据键值将新值附加到相应的列中,如果列不存在,则必须添加列并附加其值。 比如说新钥匙进来了

{GRAR:2} 
{GLPO:2}
{JLKJ:3}

example2

我知道CSV模块在这类任务中发挥得不太好。任何建议都会很有帮助

谢谢


Tags: csv数据目标for字典example键值钥匙
1条回答
网友
1楼 · 发布于 2024-10-01 05:01:11

我觉得这个设计有点刺耳。你在字典里只使用一个键有什么特别的原因吗?您可以做的是保留一个字典,其中每个值都是该特定键的元素列表。所以你的代码看起来像这样:

from collections import defaultdict

dic = defaultdict(list)

for......
    dic['XYZ'].append(val) #At the end of your for loop dic = {ABCD: [1,2,3,4], EFGH: [5,6,2,4,8]....}

rows = dic.values()
rows = zip(*rows)  #Both CSV and zip don't support variable length lines, so make all arrays of equal length by padding zeroes to the end before this line

with open('filename.csv','wb') as fp:
     fieldnames = dic.keys()
     writer = csv.writer(fp)
     writer.writerow(fieldnames)
     writer.writerows(rows)

相关问题 更多 >