在Python 3中将字典数组写入csv?

bsxbgnwa  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(137)

我已经纠结了一两天了,我似乎不能把它做对。

project_index = [
{A: ['1', '2', '3']},
{B: ['4', '5', '6']},
{C: ['7', '8', '9']},
{D: ['10', '11', '12']},
{E: ['13', '14', '15']},
{F: ['16', '17', '18']}
]

我已经尝试了很多不同的方法来尝试将其放入.CSV表中,但它总是以可笑的错误格式出现,例如它们沿对角线平铺,或者一系列的键反复出现(例如:
A、B、C、D、E、F
A、B、C、D、E、F
A、B、C、D、E、F
A、B、C、D、E、F)
而且,即使我得到了要显示的值,整个字符串数组也会显示在一个单元格中。
有没有办法让它把每个字典都变成一个列,数组中的每个字符串值都作为该列中自己的单元格?
示例:x1c 0d1x
提前感谢您!

20jt8wwn

20jt8wwn1#

假设你所有的键都是唯一的......那么这个(稍微修改):

project_index = [
{'A': ['1', '2', '3']},
{'B': ['4', '5', '6']},
{'C': ['7', '8', '9']},
{'D': ['10', '11', '12', '20']},
{'E': ['13', '14', '15']},
{'F': ['16', '17', '18']}
]

应该看起来像这样:

project_index_dict = {}
for x in project_index:
    project_index_dict.update(x)

print(project_index_dict)
# Output:
 
{'A': ['1', '2', '3'],
 'B': ['4', '5', '6'],
 'C': ['7', '8', '9'],
 'D': ['10', '11', '12', '20'],
 'E': ['13', '14', '15'],
 'F': ['16', '17', '18']}

在这一点上,与其重新发明轮子......不如使用pandas

import pandas as pd

# Work-around for uneven lengths:
df = pd.DataFrame.from_dict(project_index_dict, 'index').T.fillna('')
df.to_csv('file.csv', index=False)

输出file.csv

A,B,C,D,E,F
1,4,7,10,13,16
2,5,8,11,14,17
3,6,9,12,15,18
,,,20,,

csv模块方法:

import csv
from itertools import zip_longest, chain

header = []
for d in project_index:
    header.extend(list(d))

project_index_rows = [dict(zip(header, x)) for x in 
                      zip_longest(*chain(list(*p.values()) 
                                         for p in project_index), 
                                  fillvalue='')]

with open('file.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames = header)
    writer.writeheader()
    writer.writerows(project_index_rows)
bogh5gae

bogh5gae2#

我的解决方案不使用Pandas。计划如下:

  • 对于标题行,从字典中获取所有键
  • 对于数据行,使用zip转置列-〉行
import csv

def first_key(d):
    """Return the first key in a dictionary."""
    return next(iter(d))

def first_value(d):
    """Return the first value in a dictionary."""
    return next(iter(d.values()))
    
with open("output.csv", "w", encoding="utf-8") as stream:
    writer = csv.writer(stream)

    # Write the header row
    writer.writerow(first_key(d) for d in project_index)

    # Write the rest
    rows = zip(*[first_value(d) for d in project_index])
    writer.writerows(rows)

输出.csv的内容:

A,B,C,D,D,F
1,4,7,10,13,16
2,5,8,11,14,17
3,6,9,12,15,18

相关问题