0
a = [{'year': 222, 'title': 'abc'}, {'year': 111, 'title': 'ddd'}]

how can i convert to csv format like

b =     year, title
        222, abc
        111, ddd

I use aws lambda that I can't import pandas

6
  • 5
    Why do you need pandas? import csv... Commented Mar 26, 2018 at 2:05
  • 2
    Also, this is basically a dupe of your last question. stackoverflow.com/questions/49423634/json-to-csv-using-python Commented Mar 26, 2018 at 2:06
  • what is your "a dupe" meaning? I'm a dupe of python using I admit. Just I want to learn more about python and ask too simple question? Commented Mar 26, 2018 at 2:13
  • "I use aws lambda that I can't import pandas", means I don't want import pandas. Why you still ask me"Why do you need pandas?", So Funny? Commented Mar 26, 2018 at 2:15
  • Dup-licate. And what I meant was why you you think you need pandas? When there are other ways to write a CSV without external libraries. Commented Mar 26, 2018 at 2:23

1 Answer 1

2

Use csv.dictwriter

import csv
import io


a = [{'year': 222, 'title': 'abc'}, {'year': 111, 'title': 'ddd'}]
f = io.StringIO()
fieldnames = ['year', 'title']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for d in a:
    writer.writerow(d)

print(f.getvalue())

out:
year,title
222,abc
111,ddd
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, I using aws lambda cann't use"with open('names.csv', 'w', newline='') as csvfile:", Can you help me ?
obj = s3.get_object(Bucket='excelfile23987', Key='ttttt.json')<br> body = obj['Body']<br> a = body.read().decode('utf-8')<br> # [{'year': 222, 'title': 'abc'}, {'year': 111, 'title': 'ddd'}]
my original "a"resource is show above. I have an error in"writer.writerow(d)". "errorMessage": "'str' object has no attribute 'keys'", "errorType": "AttributeError",Please help me
Don't ask multiple question. I have answered your question. then you told you cant use file. I changed my answer. Now you want another answer.
Sorry..because I consider that cut down some useless code. And the action produce this problem. It's okay. Thank you very much answered me two time already.

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.