Search code examples
pythonpandasexport-to-csv

Python - Dictionary with arrays to csv file


I have a dictionary with four keys pointing to one array each:

import pandas as pd
import csv

complete = {'average': ['a1', 'a2', 'a3', 'a4'], 'hard': ['h1', 'h2', 'h3', 'h4','h5'], 'easy': ['e1', 'e2', 'e3', 'e4','e5','e6'], 'difficult': ['d1', 'd2', 'd3', 'd4','d5','d6','d7']}

df = pd.DataFrame(complete,orient='index').to_csv('out.csv')
df.transpose()

How can I write this dictionary to a csv file where the keys represent one column header, while arrays will fill the corresponding column underneath.

average | hard | easy | difficult |
a1      | h1   | e1   | d1        |
a2      | h2   | e2   | d2        |
a3      | h3   | e3   | d3        |
a4      | h4   | e4   | d4        |
        | h5   | e5   | d5        |
               | e6   | d6        |
                      | d7        |

As you can tell, I have tried using both the pandas and the csv library. Not sure what I am doing wrong, but this code produce the following output:

TypeError: __init__() got an unexpected keyword argument 'orient'

Solution

  • Your command

    df = pd.DataFrame(complete,orient='index').to_csv('out.csv')
    

    is missing from_dict:

    df = pd.DataFrame.from_dict(complete, orient='index').transpose()
    df.to_csv('out.csv')
    

    See also here