Skip to content Skip to sidebar Skip to footer

How To Import Dictionary To Csv

I have to export data from dictionary to csv. Dictionary contains lists. I tried to do export like this with open('info.csv', 'w',newline='')as csvfile: header = ['Club', 'Stadium

Solution 1:

You can accomplish what you want doing it like this.

import csv

withopen('info.csv', 'w', newline='') as f:
    header = info.keys()
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writeheader()
    for pivoted inzip(*info.values()):  # here we take both lists and pivot them
        writer.writerow(dict(zip(header, pivoted))) # pivoted is a 2 element tuple

I often use pandas and it's basically a oneliner with it, but it might be an overkill for your needs.

import pandas as pd
df = pd.DataFrame(info).to_csv('info.csv', index=False)

If you don't need to use pandas in general, better stick with built-in csv module.

Post a Comment for "How To Import Dictionary To Csv"