python - 从多个词典提取到 csv

标签 python list csv dictionary

我目前有一个字典列表,其中字典包含按这样的关键字排序的列表。每个词典中的列表长度相同,但每个词典的长度不同,并且每个词典中的关键字数量相同。

dicts[file1] = {Header1:[1,2,3], Header2:[4,5,6],... etc}
dicts[file2] = {Header1:[7,8,9,0], Header2:[4,3,7,7],... etc}
...
dicts[filen] = {...}

我想从每个字典中提取两个列表(例如“Header1”和“Header5”),并将它们并排放入一个 .csv 文件中,并为不长的列表填充空格。其他一些。

我几乎 100% 确定要使用 izip_longest 来执行此操作,但我正在努力寻找 izip_longest 的正确格式来完成此操作。我想我的主要障碍是我不知道要在 *args 中放入什么才能正确循环。

任何帮助将不胜感激。

编辑:按请求编写代码。

writefiel = open(somefile.csv, delimiter=',')
xcolumn = 'Header1'
ycolumn = 'Header5'
for i in len(dicts):
    for lines in izip_longest(*dicts[i][xcolumn], fillvalue=['']*2):
        writefile.writerow([dicts[i][xcolumn],dicts[i][ycolumb]])

这根本行不通,但我一直在为格式设置而绞尽脑汁,却无法找出我做错了什么。

csv 输出我希望看起来像这样。

Header1,Header5,Header1,Header5,Header1,Header5,...
1,2,4,6,3,8...
1,2,,,3,8,...

答案:

首先感谢大家对我的帮助。这就是我最终得到的结果。如果您看到任何可以改进它的方法,我很乐意听到它,这样我就可以提高我的技能。

xhold =(list(izip_longest(*(d[xcolumn] for d in dicts), fillvalue='')))
yhold =(list(izip_longest(*(d[ycolumn] for d in dicts), fillvalue='')))

writefile.writerow([xcolumn, ycolumn, '']*len(xhold))
for i in range(len(xhold)):
    row=[]
    for j in range(len(xhold[i])):
        row=row+[xhold[i][j],yhold[i][j],'']
    writefile.writerow(row)

最佳答案

也许是这个?

import itertools
itertools.izip_longest([1,2,3,4],[7,8])

lists_to_extract = ['Header1','Header2']
long_list_of_dicts = [{'Header1':[1,2,3], 'Header2':[4,5,6], 'Header3':[7,8,9]},
             {'Header1':[7,8,9,0], 'Header2':[4,3,7,7], 'Header3':[14,13,17,17]}]

print [list(itertools.izip_longest(*(d[key] for d in long_list_of_dicts),
             fillvalue=' ')) for key in lists_to_extract]
#Output:
[[(1, 7), (2, 8), (3, 9), (' ', 0)], [(4, 4), (5, 3), (6, 7), (' ', 7)]]

关于python - 从多个词典提取到 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10952770/

相关文章:

python - 0x1A 上的线路读取扼流圈

python - 使用 Python 下载自定义 Google Analytics 报告

python - 将值 append 到 Python 字典

list - 范围错误(索引): Invalid value: Valid value range is empty: 0

excel - 使用 VBA 复制粘贴脚本比较两个 CSV 文档

python - 通过python在git中自动提交

python - 将字符串添加到 python 列表的每个元素

python - python中datetime模块的isoformat函数返回不正确的偏移量

r - grid.arrange ggplot2使用列而不是使用列表按行进行绘制

python - 添加不同长度循环最小的列表