简体   繁体   中英

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.

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:

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:

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:

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

Use zip to combine those 2 lists ( 'match','player' ) into a list of tuples. 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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