简体   繁体   English

在不使用 pandas 的情况下将字典转换为 python 中的 csv?

[英]convert dictionary to csv in python without using pandas?

I have dictionay list which looks like this:我有一个看起来像这样的词典列表:

{'match':['football','cricket','baseball'],'player':['2','11','8']}

I want to convert this dictionary into csv but without using pandas.我想将这本字典转换成 csv 但不使用 pandas。

My code:我的代码:

import csv
my_dictionary = {'match':['football','cricket','baseball'],'player'['2','11','8']}
with open('data.csv', 'w') as f:
    for key in my_dictionary.keys():
        f.write("%s, %s\n" % (key, my_dictionary[key]))

The output I would like to see: output 我想看看:

match     player
football   2
cricket    11
baseball   8

So, if you want to use your technique, you can firstly write all keys into the first line as header and then iterate over the lists for the remaining rows like this:因此,如果您想使用您的技术,您可以首先将所有键写入第一行,如 header,然后遍历列表中的剩余行,如下所示:

import csv

my_dictionary = {'match':['football','cricket','baseball'],'player':['2','11','8']}
with open('data.csv', 'w') as f:
    
    headers = ', '.join(my_dictionary.keys()) + '\n'
    f.write(headers)
    
    for row in zip(*my_dictionary.values()):
        string_row = ', '.join(row) + '\n'
        f.write(string_row)

Output: Output:

match, player
football, 2
cricket, 11
baseball, 8

Use zip to combine those 2 lists ( 'match','player' ) into a list of tuples.使用 zip 将这 2 个列表 ( 'match','player' ) 组合成一个元组列表。 Join each tuple with , .,加入每个元组。 Then simply write each of those to file.然后只需将其中的每一个写入文件即可。

import csv
my_dictionary = {'match':['football','cricket','baseball'],'player':['2','11','8']}
zipList = list(zip(my_dictionary['match'],my_dictionary['player']))
zipList = [','.join(x) for x in zipList]


with open('data.csv', 'w') as f:
    headers = ','.join(my_dictionary.keys()) + '\n'
    f.write(headers)
    for each in zipList:
        f.write("%s\n" % (each))

To avoid using Pandas, use the built in CSV library:为避免使用 Pandas,请使用内置的 CSV 库:

import csv
    
my_dictionary = {'match':['football','cricket','baseball'],'player':['2','11','8']}

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(my_dictionary.keys())
    csv_output.writerows([*zip(*my_dictionary.values())])

This would produce output.csv containing:这将产生output.csv包含:

match,player
football,2
cricket,11
baseball,8

Your dictionary keys give you the header, and if you use a standard *zip(*xxx) trick to transpose the entries you can write all the rows in one go.您的字典键为您提供 header,如果您使用标准的*zip(*xxx)技巧来转置条目,您可以将所有行写在一个 go 中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM