在python中写一个文件中的字典列表

时间:2015-05-20 13:02:29

标签: python dictionary

我的目标是将字典写入文件

f = open(...)
i = 0
for dic in dicolist:
    w = csv.DictWriter(f, dic.keys(), lineterminator='\n')
    if i == 0:
        w.writeheader()
        i = 1
    w.writerow(dic)

我的目标是在文件中写下这样的词典:

field1,field2,field3 #name of the rows of the dictionary
0,1,1 #first dictionary
1,1,1 #second dictionary
2,2,2 #third dictionary

我不介意田地的顺序, 我希望第一个字典的field1与第二个字典的field2位于同一个地方。

例如,首先会有第一个字典的第一个字段 然后在下一行,它将是第二个字典的第三个字段。

我应该用什么来编写好的词典?

我想要的是:

fieldx, fieldy, fieldz
fieldx of first dictionary, fieldy of first dictionary, fieldz of first dictionary
fieldx of second dictionary, fieldy of second dictionary, fieldz of second dictionary

2 个答案:

答案 0 :(得分:0)

如果您的词典都具有相同的键,只需获取一次字段名称并在迭代字典时使用单个编写器:

with open(...) as csvfile:
     FIELD_NAMES = [...] # keys of your dictionary 
     writer = csv.DictWriter(csvfile, fieldnames=FIELD_NAMES, lineterminator='\n')
     writer.writeheader()
     for dic in dicolist:
         writer.writerow(dic)

答案 1 :(得分:0)

import csv

dicts = [
    {'foo': 1, 'bar': 2},
    {'foo': 1, 'spam': 3},
    {'spam': 3, 'bar': 2},
]

out_filename = 'dicts.csv'

# we use set to ensure uniqueness of header names and to be sure
# that we have all column names even if some are missing in one dict:
keys = (set(d.keys()) for d in dicts)
field_names = set.union(*keys)

with open(out_filename, 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=list(field_names))
    writer.writeheader()
    for dct in dicts:
        writer.writerow(dct)

with open(out_filename) as f:
    print f.read()