0

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.

1
  • please make sure your dictionary syntax is correct . Commented Aug 20, 2015 at 13:32

2 Answers 2

1
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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton@Rajesh. Great help indeed.
@Rajesh_Sharma - please mark it as answered, if you feel i have answered your question correctly
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.