如何将字典列表写入具有多个值的CSV

时间:2017-09-28 12:12:29

标签: python csv dictionary

我在" my_list"中有一个词典列表。如下:

my_list=[{'Id': '100', 'A': [val1, val2], 'B': [val3, val4], 'C': [val5,val6]}, 
         {'Id': '200', 'A': [val7, val8], 'B': [val9, val10], 'C': 
         [val11,val12],
         {'Id': '300', 'A': [val13, val14], 'B': [val15, val16], 'C':   
         [val17,val18]}]

我想将此列表写入CSV文件,如下所示:

ID,  A,     AA,    B,     BB,    C,     CC
100, val1,  val2,  val3,  val4,  val5,  val6
200, val7,  val8,  val9,  val10, val11, val12
300, val13, val14, val15, val16, val17, val18   

有谁知道我该怎么处理它?<​​/ p>

3 个答案:

答案 0 :(得分:1)

Tablib应该做的伎俩

我将这个例子留在他们的首页(你可以适应.csv格式):

>>> data = tablib.Dataset(headers=['First Name', 'Last Name', 'Age'])
>>> for i in [('Kenneth', 'Reitz', 22), ('Bessie', 'Monke', 21)]:
...     data.append(i)


>>> print(data.export('json'))
[{"Last Name": "Reitz", "First Name": "Kenneth", "Age": 22}, {"Last Name": "Monke", "First Name": "Bessie", "Age": 21}]

>>> print(data.export('yaml'))
- {Age: 22, First Name: Kenneth, Last Name: Reitz}
- {Age: 21, First Name: Bessie, Last Name: Monke}

>>> data.export('xlsx')
<censored binary data>

>>> data.export('df')
  First Name Last Name  Age
0    Kenneth     Reitz   22
1     Bessie     Monke   21

答案 1 :(得分:0)

你可以这样做......(根据需要用csv writerow替换打印)

print(['ID', 'A', 'AA', 'B', 'BB', 'C', 'CC'])
for row in my_list:
    out_row = []
    out_row.append(row['Id'])
    for v in row['A']:
        out_row.append(v)
    for v in row['B']:
        out_row.append(v)
    for v in row['C']:
        out_row.append(v)
    print(out_row)

答案 2 :(得分:0)

您可以使用pandas来解决问题:

my_list = [{'Id': '100', 'A': [val1, val2], 'B': [val3, val4], 'C': [val5, val6]},
           {'Id': '200', 'A': [val7, val8], 'B': [val9, val10], 'C': [val11, val12]},
           {'Id': '300', 'A': [val13, val14], 'B': [val15, val16], 'C': [val17, val18]}]

index = ['Id', 'A', 'AA', 'B', 'BB', 'C', 'CC']

df = pd.DataFrame(data=my_list)
for letter in ['A', 'B', 'C']:
    first = []
    second = []
    for a in df[letter].values.tolist():
        first.append(a[0])
        second.append(a[1])
    df[letter] = first
    df[letter * 2] = second

df = df.reindex_axis(index, axis=1)
df.to_csv('out.csv')

这会产生以下输出dataframe

    Id   A  AA   B  BB   C  CC
0  100   1   2   3   4   5   6
1  200   7   8   9  10  11  12
2  300  13  14  15  16  17  18

这是out.csv - 文件:

,Id,A,AA,B,BB,C,CC
0,100,1,2,3,4,5,6
1,200,7,8,9,10,11,12
2,300,13,14,15,16,17,18

请参阅有关csv - 功能(csv)的pandas文档。

  

将DataFrame写入以逗号分隔的值(csv)文件