Search code examples
python-3.xexport-to-csvdefaultdict

How to write a defaultdict(list) values into separate rows in csv file using Python?


I have the following defaultdict(list) and trying to write its key as the header and its values in separate rows using csv writer.

defaultdict(<class 'list'>, {'Replier Username': ['vindyne8', 'vindyne8', 'denisc', 'denisc', 'vindyne8', 'vindyne8', 'denisc', 'denisc', 'vindyne8', 'vindyne8', 'denisc', 'vindyne8', 'denisc', 'igotBAWS', 'vindyne8', 'vindyne8', 'OneChain', 'denisc', 'denisc', 'vindyne8', 'vindyne8', 'denisc', 'denisc', 'vindyne8', 'denisc', 'denisc', 'vindyne8', 'denisc']})

I would like to get the following result in the csv file:

Replier Username

vindyne8
vindyne8
denisc
denisc
vindyne8
.
.
.

I tired the following code but it is writing the key and values in separate columns not separate rows.

with open('myfile.csv', 'w') as f:
    writer= csv.writer(f)
    for k,v in replier_username_dict.items():
        writer.writerow([k] + v)

Anyone has idea? Thank you.


Solution

  • You're almost there. You just need to loop through the values since it contains a list.

    >>> for key, values in replier_username_dict.items():
    ...     csvwriter.writerow ([key])
    ...     for value in values:
    ...         csvwriter.writerow ([value])
    ... 
    Replier Username
    vindyne8
    vindyne8
    denisc
    denisc
    vindyne8