Rajesh_Sharma
Rajesh_Sharma

Reputation: 21

CSV file from a list with multiple dictionaries in Python?

I have data of following form:

{'count': '274',  'file_type': 'json', 'limit': '100000',    observation_end': '9999-12-31',    'observation_start': '1776-07-04',    'observations': "[{'date': '1947-01-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '3.962'}, {'date': '1947-04-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '4.052'}, {'date': '1947-07-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '4.172'}, {'date': '1947-10-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '4.270'}, {'date': '1948-01-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '4.372'}, {'date': '1948-04-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '4.432'}, {'date': '1948-07-01', 'realtime_start': '2015-08-20', 'realtime_end': '2015-08-20', 'value': '4.521'}]

I want to create CSV or Excel file from it so that different values appear on different rows. E.g data 1948-07-01 value 4521. Is it possible and how? I tried following:

writer = csv.writer(open('dict.csv', 'wb'))
for key, value in mydict.items():
    writer.writerow([key, value])

But getting last row containing all the dictionaries of list in single row.

Upvotes: 0

Views: 717

Answers (2)

Thothadri Rajesh
Thothadri Rajesh

Reputation: 522

import ast # since your observations seems to be a string 
a=your_dictionary
observations=ast.literal_eval(a["observations"]) # this will convert this string to list
headers=observations[0].keys() 
writer = csv.writer(open('dict.csv', 'wb'))
writer.writerow(headers) # to make sure your headings are date,realtime_start etc
for data in observations:
    row=[data[header] for header in headers] #will create the row in same order as headers
    writer.writerow(row)

Upvotes: 1

amirouche
amirouche

Reputation: 7873

You must first write the headers with the keys and then write your values.

Given the fact that all your data has the sames keys, the following will work:

writer = csv.writer(open('dict.csv', 'wb'))
# retrieve the first dict to  write the csv header:
header = data[0].keys()
writer.writerow(header)
# iterate over data:
for data in datas:
    writer.writerow(data.values())

Remember to use collections.OrderedDict to make sure that .keys and .values methods return items in the same order.

Upvotes: 0

Related Questions