![](/img/trans.png)
[英]convert dictionary with lists to csv file where the columns are the keys and the values are in the rows
[英]Write Python dictionary to CSV where where keys= columns, values = rows
我有一个字典列表,我希望能够在 Excel 中打开并正确格式化。 这是我到目前为止所拥有的,使用 csv:
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(ipath, 'wb')
writer = csv.writer(ofile, dialect = 'excel')
for items in list_of_dicts:
for k,v in items.items():
writer.writerow([k,v])
显然,当我在 Excel 中打开输出时,它的格式如下:
key value
key value
我想要的是这个:
key key key
value value value
我无法弄清楚如何做到这一点,因此将不胜感激。 另外,我希望列名是字典键,而不是默认的“A、B、C”等。对不起,如果这是愚蠢的。
谢谢
csv 模块为此提供了一个DictWriter类,在另一个 SO answer 中对此进行了很好的介绍。 关键点是在实例化 DictWriter 时需要知道所有列标题。 您可以从 list_of_dicts 构建字段名称列表,如果是这样,您的代码将变为
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(out_path, 'wb')
fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
writer.writeheader() # Assumes Python >= 2.7
for row in list_of_dicts:
writer.writerow(row)
out_file.close()
我构建 fieldnames 的方式是扫描整个list_of_dicts
,所以它会随着大小的增加而变慢。 您应该直接从数据源构建fieldnames
,例如,如果数据源也是 csv 文件,您可以使用 DictReader 并使用fieldnames = reader.fieldnames
。
您还可以使用对writer.writerows(list_of_dicts)
的单个调用替换for
循环并使用with
块来处理文件关闭,在这种情况下,您的代码将变为
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
with open(out_path, 'wb') as out_file:
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
writer.writeheader()
writer.writerows(list_of_dicts)
您需要编写 2 个单独的行,一个是键,一个是值,而不是:
writer = csv.writer(ofile, dialect = 'excel')
writer.writerow([k for d in list_of_dicts k in d])
writer.writerow([v for d in list_of_dicts v in d.itervalues()])
这两个列表推导式首先从输入列表中的字典中提取所有键,然后提取所有值,将它们组合成一个列表以写入 CSV 文件。
我认为最有用的是逐列写入,因此每个键都是一列(适合以后进行数据处理并用于例如 ML)。
昨天我在弄清楚它时遇到了一些麻烦,但我想出了我在其他网站上看到的解决方案。 但是,从我看来,不可能一次浏览整个字典,我们必须将其划分为较小的字典(我的 csv 文件最后有 20k 行 - 被调查的人,他们的数据和答案。我这样做了这个:
# writing dict to csv
# 'cleaned' is a name of the output file
# 1 header
# fildnames is going to be columns names
# 2 create writer
writer = csv.DictWriter(cleaned, d.keys())
# 3 attach header
writer.writeheader()
# write separate dictionarties
for i in range(len(list(d.values())[0])):
writer.writerow({key:d[key][i] for key in d.keys()})
我看到我的解决方案还有一个 for 循环,但另一方面,我认为它需要更少的内存(但是,我不确定!!)希望它可以帮助某人;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.