将字典导出到csv文件

时间:2017-10-22 05:38:04

标签: python python-3.x csv dictionary export

我有一本看起来像这样的字典

file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] }

我想将“Formation”和“Depth”作为标题,并希望文件在我的输出csv文件中垂直列出。所以,

Formations       Depth
  some1            1 
  some2            2
  some3            3
像这样的事情。

如何做到这一点?我可以将深度列表[1,2,3]转换为字符串列表,如[“1”,“2”,“3”],如果有必要的话。

要COLDSPEED,这就是它在输出文件中的样子。

Formations           Depth
  (blank)           (blank) 
   some1               1
  (blank)           (blank)
   some2               2
  (blank)           (blank)
   some3               3

(空白)这里只是表示没有任何内容的空行。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

可以使用DictWriter,但只需拨打zip然后将每对写入您的CSV就更容易了。

import csv

file = {"Formations" : ["some1","some2","some3"], "Depth": [1,2,3] }

with open(...) as f:
    w = csv.writer(f)
    for x, y in zip(file['Formations'], file['Depth']):
        w.writerow([x, y])
相关问题