简体   繁体   English

将 Python 字典写入 CSV,其中键 = 列,值 = 行

[英]Write Python dictionary to CSV where where keys= columns, values = rows

I have a list of dictionaries that I want to be able to open in Excel, formatted correctly.我有一个字典列表,我希望能够在 Excel 中打开并正确格式化。 This is what I have so far, using csv:这是我到目前为止所拥有的,使用 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])

Obviously, when I open the output in Excel, it's formatted like this:显然,当我在 Excel 中打开输出时,它的格式如下:

key  value
key  value

What I want is this:我想要的是这个:

key   key   key

value value value

I can't figure out how to do this, so help would be appreciated.我无法弄清楚如何做到这一点,因此将不胜感激。 Also, I want the column names to be the dictionary keys, in stead of the default 'A, B, C' etc. Sorry if this is stupid.另外,我希望列名是字典键,而不是默认的“A、B、C”等。对不起,如果这是愚蠢的。

Thanks谢谢

The csv module has a DictWriter class for this, which is covered quite nicely in another SO answer . csv 模块为此提供了一个DictWriter类,在另一个 SO answer 中对此进行了很好的介绍。 The critical point is that you need to know all your column headings when you instantiate the DictWriter.关键点是在实例化 DictWriter 时需要知道所有列标题。 You could construct the list of field names from your list_of_dicts, if so your code becomes您可以从 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()

The way I've constructed fieldnames scans the entire list_of_dicts , so it will slow down as the size increases.我构建 fieldnames 的方式是扫描整个list_of_dicts ,所以它会随着大小的增加而变慢。 You should instead construct fieldnames directly from the source of your data eg if the source of your data is also a csv file you can use a DictReader and use fieldnames = reader.fieldnames .您应该直接从数据源构建fieldnames ,例如,如果数据源也是 csv 文件,您可以使用 DictReader 并使用fieldnames = reader.fieldnames

You can also replace the for loop with a single call to writer.writerows(list_of_dicts) and use a with block to handle file closure, in which case your code would become您还可以使用对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)

You need to write 2 separate rows, one with the keys, one with the values, instead:您需要编写 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()])

The two list comprehensions extract first all the keys, then all the values, from the dictionaries in your input list, combining these into one list to write to the CSV file.这两个列表推导式首先从输入列表中的字典中提取所有键,然后提取所有值,将它们组合成一个列表以写入 CSV 文件。

I think that the most useful is to write the column by column, so each key is a column (good for later on data processing and use for eg ML).我认为最有用的是逐列写入,因此每个键都是一列(适合以后进行数据处理并用于例如 ML)。

I had some trouble yesterday figuring it out but I came up with the solution I saw on some other website.昨天我在弄清楚它时遇到了一些麻烦,但我想出了我在其他网站上看到的解决方案。 However, from what I see it is not possible to go through the whole dictionary at once and we have to divide it on smaller dictionaries (my csv file had 20k rows at the end - surveyed person, their data and answers. I did it like this:但是,从我看来,不可能一次浏览整个字典,我们必须将其划分为较小的字典(我的 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()}) 

I see my solution has one more for loop but from the other hand, I think it takes less memory (but, I am not sure!!) Hope it'd help somebody ;)我看到我的解决方案还有一个 for 循环,但另一方面,我认为它需要更少的内存(但是,我不确定!!)希望它可以帮助某人;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将带有列表的字典转换为csv文件,其中列为键,值在行中 - convert dictionary with lists to csv file where the columns are the keys and the values are in the rows 将python字典写入CSV列:第一列的键,第二列的值 - Write python dictionary to CSV columns: keys to first column, values to second python dictionary将键的值放入一个列表,其中键位于另一个列表中 - python dictionary put values of keys into a list where the keys are in another list Python:返回列的键字典,单元格等于值的行索引列表的值 - Python: return dictionary of keys for columns, values for lists of row indexes where the cell is equal to a value 将字典转换为 dataframe ,其中键和值都有自己的列 - converting a dictionary to dataframe where keys and values each have their own columns Pandas:将字典转换为 dataframe,其中键和值是列 - Pandas: Convert dictionary to dataframe where keys and values are the columns 将字典列表写到csv中,其中字典值是列表 - Write a list of dictionaries to csv where the dictionary values are lists 如何从另一个python字典中的一个字典中获得相应的列表值,在列表中它们被列为键,比较并打印出csv? - How can I get corresponding list values in one dictionary from another python dictionary where they are listed as keys, compare and print out a csv? 如何在Python中编写具有多个键的字典,每个键具有多个值到csv? - How to write a dictionary with multiple keys, each with multiple values to a csv in Python? Python:将字典键转换为 csv 标题和值转换为行 - Python: Convert dictionary keys into csv headers and values into rows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM