将dict列表写为csv的连续列

时间:2017-03-16 05:33:17

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

我正在尝试写一个dict列表,说: list = [dict1, dict2,...,] 以下内容: dict1 = {key1: value1, key2: value2,...} 我怎样才能将每个dict连续编写成2列到一个单独的csv文件中?您将第1列和第2列属于dict1的键和值,第3列和第4列包含dict2的键和值...依此类推?

3 个答案:

答案 0 :(得分:0)

假设您的列表为l=[{1: 2, 3: 4, 5: 6}, {9: 10, 11: 12, 7: 8}, {17: 18, 13: 14, 15: 16}]。首先从每个字典中提取键和值:

[l0.items() for l0 in l]
# [dict_items([(1, 2), (3, 4), (5, 6)]), 
#  dict_items([(9, 10), (11, 12), (7, 8)]), 
#  dict_items([(17, 18), (13, 14), (15, 16)])]

现在,让我们将每个元组列表组合成一个平面列表:

from itertools import chain
[list(chain.from_iterable(l0.items())) for l0 in l]
# [[1, 2, 3, 4, 5, 6], 
#  [9, 10, 11, 12, 7, 8], 
#  [17, 18, 13, 14, 15, 16]]

结果可以直接送到CSV编写器。

答案 1 :(得分:0)

使用itertools链:

import csv
from itertools import chain

dictionary = [{'key1': 'value1'}, {'key2': 'value2'},
              {'key3': 'value3'}, {'key4': 'value4'}]

with open('file', 'w') as fh:
    csv_file = csv.writer(fh)
    csv_file.writerow(chain(*(i for e in dictionary for i in zip(e.keys(), e.values()))))

结果:

cat file
key1,value1,key2,value2,key3,value3,key4,value4

答案 2 :(得分:0)

请尝试此程序,希望它能产生您需要的输出,

import csv

dict1 = {'key11' : 'value11', 'key12' : 'value12', 'key13' : 'value13'}
dict2 = {'key21' : 'value21', 'key22' : 'value22', 'key23' : 'value23'}
dict3 = {'key31' : 'value31', 'key32' : 'value32', 'key33' : 'value33'}

list1 = [dict1, dict2, dict3]

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    for entry in list1:
        lis = []
        for key,values in sorted(entry.items()):
            lis.append(key)
            lis.append(values)
        w.writerow(lis)

输出

key11,value11,key12,value12,key13,value13
key21,value21,key22,value22,key23,value23
key31,value31,key32,value32,key33,value33

请让我知道任何疑问的内容。