Hassan Baig
Hassan Baig

Reputation: 15834

Writing a list of dictionaries to multiple columns (and rows)

I have a list of dictionaries of length n. Typical contents are:

[{"description":"Lorem, ipsum, dolor, sit amet","error":"text_too_long"},{'description':'Sed ut perspiciatis, unde omnis','error':'text_too_long'},...]

I'm trying to write this to a CSV file, where "description" and "error" form two columns, and the rows are each element of the list.

I've tried:

import csv, ast
list_ = list_of_dictionaries #as a string
with open('data.csv','wb') as f:
    wtr = csv.writer(f)
    for string in list_:
        dictionary = ast.literal_eval(string) #converting to dictionary
        to_write = [dictionary["description"],dictionary["error"]]
        wtr.writerow([to_write])

This merely gives me the entire dictionary in a single column (but rows are fine). What am I doing wrong?

Upvotes: 0

Views: 60

Answers (2)

njoosse
njoosse

Reputation: 549

The dictionaries can be set directly, you do not need the ast function.

for dictionary in list_:
    to_write = [dictionary["description"],dictionary["error"]]
    wtr.writerow(to_write) # Not [to_write]

will write the dictionary in 2 columns.

Upvotes: 1

boot-scootin
boot-scootin

Reputation: 12515

Can you not use pandas?

data = [{"description":"Lorem, ipsum, dolor, sit amet","error":"text_too_long"},{'description':'Sed ut perspiciatis, unde omnis','error':'text_too_long'}]

import pandas as pd

df = pd.DataFrame(data)

You get this:

df
Out[246]: 
                       description          error
0    Lorem, ipsum, dolor, sit amet  text_too_long
1  Sed ut perspiciatis, unde omnis  text_too_long

And then use to_csv:

df.to_csv('data.csv', index=False)

Upvotes: 1

Related Questions