CSV字典列表清单

时间:2018-12-03 00:31:31

标签: python csv dictionary

我知道我可以将字典列表直接写到CSV文件中。同样,是否有直接方法将词典列表列表写入python中的csv文件,而无需手动遍历每一行?

样本数据

[[{'e': 46, 'p': 100, 'n': 0, 'a': 100, ...}, 
  {'e': 29, 'p': 40, 'n': 1, 'a': 40, ...}, ...],
 [{...}, ...]

期望的格式

e,p,n,a,....
46,100,0,100,....
29,40,1,40,...
.......

注意,这不是词典列表,而是词典列表

4 个答案:

答案 0 :(得分:6)

没有熊猫,您可以使用itertools.chain获取所有词典的扁平列表,然后使用csv.DictWriter将其写入CSV文件:

import csv
from itertools import chain

data = [
    [{'e': 46, 'p': 100, 'n': 0, 'a': 100}, 
     {'e': 29, 'p': 40, 'n': 1, 'a': 40}],
    [{'e': 56, 'p': 200, 'n': 23, 'a': 10}, 
     {'e': 22, 'p': 41, 'n': 11, 'a': 420}]]

fieldnames = ['e', 'p', 'n', 'a']
with open('mydata.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(chain.from_iterable(data))

输出(mydata.csv)

e,p,n,a
46,100,0,100
29,40,1,40
56,200,23,10
22,41,11,420

答案 1 :(得分:2)

必须有一种方法可以仅使用核心Python来完成您的任务,但我会选择Pandas:

import pandas as pd
d = yourListOfListsOfDictionaries
df = pd.concat(map(pd.DataFrame, d), sort=True)
#     a   e  n    p
#0  100  46  0  100
#0   40  29  1   40
df.to_csv(index=False)
#'a,e,n,p\n100,46,0,100\n40,29,1,40\n'

答案 2 :(得分:2)

如果您希望键集是字典列表中所有词典的并集,则可以执行以下操作:

import csv
x = \
[[{'e': 46, 'p': 100, 'n': 0, 'a': 100},
  {'e': 29, 'p': 40, 'n': 1, 'a': 40}],
 [{'e': 19, 'p': 10, 'n': 1, 'a': 10, 'b':8}]]

key_dict = {}
for l in x:
    for d in l:
        for k in d:
            key_dict[k] = None

with open('file.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, key_dict.keys())
    writer.writeheader()
    for l in x:
        for d in l:
            writer.writerow(d)

结果:

a,p,b,e,n
100,100,,46,0
40,40,,29,1
10,10,8,19,1

答案 3 :(得分:2)

如果字典具有相同的格式,则像这样平整列表(假设它确实是二维列表):

data = [
    [{'a': 10, 'b': 20, 'c': 30}],
    [{'a': 20, 'b': 30, 'c': 40},
     {'a': 30, 'b': 40, 'c': 50}]
]
rows = [item for sublist in data for item in sublist]

然后将您的行写入CSV:

with open('my_data.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, rows[0].keys())
    dict_writer.writeheader()
    dict_writer.writerows(rows)

以下两个帖子的组合:

How to make a flat list out of list of lists?

How do I convert this list of dictionaries to a csv file?