0

我在字典中有一本字典,如下所示:

{'ID1':{'sam':1,'maj':5, 'tif':7, 'paul':1},
 'ID2':{'maj':4,'bib':5},
 ...}

如何将其写入 CSV 文件?我想为主键设置单独的积云,为内部键设置单独的列

4

2 回答 2

0

希望这能为您指明正确的方向。假设您想按 ID 的排序顺序排列。

>> import csv
>>> d = {'ID1':{'sam':1,'maj':5, 'tif':7, 'paul':1},'ID2':{'maj':4,'bib':5},}
>>> with open('test.csv', 'w') as f:
        fieldnames = ('sam', 'maj', 'tif', 'paul', 'bib')
        w = csv.DictWriter(f, fieldnames)
        for k, row in sorted(d.items()):
            w.writerow(row)


>>> with open('test.csv') as f: # showing contents
        print f.read()


1,5,7,1,    
,4,,,5
于 2013-04-12T11:33:51.783 回答
0

在此处输入图像描述我想这就是你要找的东西:

import csv
with open('/home/test/kelvin1/add.csv', 'wb') as csvfile:
    kev = csv.writer(csvfile, delimiter=' ',
                 quotechar='|', quoting=csv.QUOTE_MINIMAL)
    k ={'ID1':{'sam':1,'maj':5,'tif':7,'paul':1},'ID2':{'maj':4,'bib':5}}
    for i in k:
          kev.writerow(i)
          for j in k[i]:
              kev.writerow(j)
              kev.writerow('%d' % (k[i][j]))

这段代码对我有用

于 2013-04-12T13:11:10.630 回答