Mixter
Mixter

Reputation: 193

Write dictionary of different size lists to a CSV via Python

I would like to write the following python dictionary:

dicty = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\\']}

To a CSV file, in the following format:

enter image description here

Current code:

import csv

dicty = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\\']}

with open('data.csv', 'w') as f:
    for key in dicty.keys():
        f.write("%s, %s\n" % (key, dicty[key]))

Yields:

enter image description here

Upvotes: 1

Views: 512

Answers (1)

Kraigolas
Kraigolas

Reputation: 5590

You can use this code:

import pandas as pd 
dictionary = {'Odd': [1,3,5,7,9], 'Even': [2,4,6], 'Operations': ['-','+','*','\\']}

# These lines are because your lists are not all of the same length 
df = pd.DataFrame.from_dict(dictionary, orient='index')
df = df.transpose()

# Pandas was converting the "9" in odd to a float, this undoes that 
df["Odd"] = pd.to_numeric(df["Odd"], downcast="integer")

# index = False says don't include the index that pandas slaps onto your data  
# This writes to output.csv as you'd expect 
df.to_csv("output.csv", index = False)

Upvotes: 1

Related Questions