Search code examples
pythoncsvdictionaryfile-conversionmultivalue

How to write multiple valued dictionaries to csv using csv module?


import csv

dict = {'a':[1,4],'b':[2,3]}

I want to convert this module into a csv file with name 'rating.csv'

Desired Output:

name,maths,science
a,1,4
b,2,3

Solution

  • You may iterate through your dictionary keys and values, join the two to a single list and then use csv.writerow for each entry:

    import csv
    d = {'a':[1,4],'b':[2,3]}
    with open("rating.csv", "w", newline="") as fh:
        writer = csv.writer(fh)
        writer.writerow(["name", "maths", "science"])
        for key, values in d.items():
            writer.writerow([key] + values)
    

    Note that I have re-named dict to d as you should avoid using builtin names for your variables.

    Output in "rating.csv":

    name,maths,science                                                              
    a,1,4                                                                           
    b,2,3