将列表字典写入CSV fi

2024-06-16 08:49:38 发布

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

我正在努力把一个列表字典写到一个.csv文件中。

我的字典是这样的:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]

我希望.csv文件看起来像:

key1  key2  key3
1     4     7  
2     5     8
3     6     9

首先我写下标题:

outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())

到目前为止还不错。。。然而,我的问题是我不知道如何将一个列表分配给相应的列。e、 g.:

for i in range(0,len(dict[key1])):
    writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])

将随机填充列。另一个问题是,我必须手工填写关键字,不能用它来编写另一本有4个关键字的词典。


Tags: 文件csv标题列表字典关键字opendict
3条回答

即使键中的列表具有不同的长度,这也会起作用。

    with myFile:  
        writer = csv.DictWriter(myFile, fieldnames=list(clusterWordMap.keys()))   
        writer.writeheader()
        while True:
            data={}
            for key in clusterWordMap:
                try:
                    data[key] = clusterWordMap[key][ind]
                except:
                    pass
            if not data:
                break
            writer.writerow(data)

您可以使用pandas将其保存到csv:

df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)

如果您不关心列的顺序(因为字典是无序的),您只需使用zip()

d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile)
   writer.writerow(d.keys())
   writer.writerows(zip(*d.values()))

结果:

key3    key2    key1
7       4       1
8       5       2
9       6       3

如果您真的关心订单,您需要对密钥进行排序:

keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile, delimiter = "\t")
   writer.writerow(keys)
   writer.writerows(zip(*[d[key] for key in keys]))

结果:

key1    key2    key3
1       4       7
2       5       8
3       6       9

给定

dict = {}
dict['key1']=[1,2,3]
dict['key2']=[4,5,6]
dict['key3']=[7,8,9]

以下代码:

COL_WIDTH = 6
FMT = "%%-%ds" % COL_WIDTH

keys = sorted(dict.keys())

with open('out.csv', 'w') as csv:
    # Write keys    
    csv.write(''.join([FMT % k for k in keys]) + '\n')

    # Assume all values of dict are equal
    for i in range(len(dict[keys[0]])):
        csv.write(''.join([FMT % dict[k][i] for k in keys]) + '\n')

生成一个csv,它看起来像:

key1  key2  key3
1     4     7
2     5     8
3     6     9

相关问题 更多 >