简体   繁体   English

在 CSV 中编写字典列表

[英]Writing a list of dictionaries in CSV

The next problem you have a list of dictionaries of the format下一个问题你有一个格式的字典列表

[{'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14}, 
 {'a': 20, 'b': 21, 'c': 22, 'd': 23, 'e': 24}, 
 {'a': 30, 'b': 31, 'c': 32, 'd': 33, 'e': 34}, 
 {'a': 40, 'b': 41, 'c': 42, 'd': 43, 'e': 44}]

which you want to move to CSV-file, looking like你想移动到 CSV 文件,看起来像

"a","b","c","d","e"  
 10,11,12,13,14
 20,21,22,23,24
 30,31,32,33,34
 40,41,42,43,44

Problem is that when you start code:问题是当你开始代码时:

def write_csv_from_list_dict(filename, table, fieldnames, separator, quote):
    table = []
    for dit in table:
        a_row = []
        for fieldname in fieldnames:
            a_row.append(dit[fieldname])
        table.append(a_row)
    file_handle = open(filename, 'wt', newline='')
    csv_write = csv.writer(file_handle,
                           delimiter=separator,
                           quotechar=quote,
                           quoting=csv.QUOTE_NONNUMERIC)
    csv_write.writerow(fieldnames)
    for row in table:
        csv_write.writerow(row)
    file_handler.close()

raising error引发错误

(Exception: AttributeError) "'list' object has no attribute 'keys'" 
at line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames

Why to be so hard to say, explicitly to close a file, not a string.为什么这么难说,明确地关闭一个文件,而不是一个字符串。

The below code should work下面的代码应该工作

data = [{'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14},
        {'a': 20, 'b': 21, 'c': 22, 'd': 23, 'e': 24},
        {'a': 30, 'b': 31, 'c': 32, 'd': 33, 'e': 34},
        {'a': 40, 'b': 41, 'c': 42, 'd': 43, 'e': 44}]
keys = data[0].keys()
with open('data.csv', 'w') as f:
    f.write(','.join(keys) + '\n')
    for entry in data:
        f.write(','.join([str(v) for v in entry.values()]) + '\n')

data.csv数据.csv

a,b,c,d,e
10,11,12,13,14
20,21,22,23,24
30,31,32,33,34
40,41,42,43,44

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

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