Write python dictionary to CSV columns: keys to first column, values to second

16,479

Solution 1

You could simply do in python 2.X :

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for row in myDict.iteritems():
        writer.writerow(row)

For python 3.X, change the for loop line to for row in myDict.items():

Solution 2

A slightly shorter version is to do:

rows = myDict.iteritems()

(Or .items() for Python 3.)

To get the ; separator, pass delimiter to csv.reader or csv.writer. In this case:

writer = csv.writer(f, delimiter=';')
Share:
16,479
user25976
Author by

user25976

Updated on June 05, 2022

Comments

  • user25976
    user25976 almost 2 years

    I'm looking for a way to write a python dictionary to columns (keys in first column and values in second). This link shows how to write a list to a column, but am wondering if there is a way to do this without converting my dictionary to two zipped lists.

    myDict = {1:'a', 2:'b', 3:'c'}
    
    keyList = myDict.keys()
    valueList = myDict.values()
    
    rows = zip(keyList, valueList)
    
    with open('test.csv', 'wb') as f:
        writer = csv.writer(f)
        for row in rows:
            writer.writerow(row)
    

    desired result:

    1;a
    2;b
    3;c
    
  • zsquare
    zsquare almost 10 years
    This would yield 1;2;3\na;b;c, not the desired output.
  • Michael Romrell
    Michael Romrell over 9 years
    THANK YOU! It took me forever to find a suitable answer to this you helped me find my solution: with open('manifesttest2.csv', "wb") as f: writer = csv.writer(f, delimiter=',') writer.writerow(amazonData)
  • Anorov
    Anorov over 9 years
    @MichaelRomrell CSV's reader and writer objects should be using , as a delimiter by default (CSV stands for comma-separated values). Does it work without passing the parameter?