简体   繁体   English

在python文件中写入字典列表

[英]Write list of dictionary in a file in python

My goal is to write dictionaries into a file 我的目标是将字典写入文件

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)

My goal is to write the dictionaries like this in a file: 我的目标是将这样的字典写入文件中:

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

I don't mind about the order of the fields, I want the field1 of the first dictionary to be at the same place as the field2 of the second dictionary. 我不在乎字段的顺序,我希望第一个字典的field1与第二个字典的field2位于同一位置。

For instance there will be at first the first field of the first dictionary and then on the next line, it will be the third field of the second dictionary. 例如,首先是第一个字典的第一个字段,然后在下一行,它将是第二个字典的第三个字段。

What should I use to write the dictionaries in a good order? 我应该用什么来整理字典?

What I want is: 我想要的是:

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

If your dictionaries all have the same keys, just get the field names once and use a single writer while iterating over your dictionaries: 如果您的字典都具有相同的键,则只需一次获取字段名称并在迭代字典时使用单个编写器即可:

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)
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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM