Python: How To Create A Csv String (no File) From A List Of Dictionaries?
In Python I have a list of dictionaries like this:
[
{
"col2": "2",
"id": "1",
"col3": "3",
"col1": "1"
},
{
"col2": "4",
"id": "2",
"col3": "6",
"col1": "2"
},
{
"col1": "1",
"col2": "4",
"id": "3",
"col3": "7"
}
]
and I need to convert this to a string in csv format including a header row. (For starters let's not care about column and row delimiters...) So, ideally the result would be:
id,col1,col2,col3
1,1,2,3
2,2,4,6
3,1,4,7
("ideally" because the column order does not really matter; having the "id" column first would be nice though...)
I have searched SOF and there are a number of similar questions but the answers always involve creating a csv file using csv.DictWriter. I don't want to create a file, I just want that string!
Of course, I could loop over the list and inside this loop loop over the dictionary keys and in this way create the csv string using string operations. But surely there must be some more elegant and efficient way of doing this?
Also, I'm aware of the Pandas library but I am trying to do this in a very limited environment where I would prefer to use only built-in modules.
Answer
You can use io.StringIO
to write to a 'string' instead of a file. Using the example of csv.DictWriter
we get the following code:
import csv
import io
data = [...] # your list of dicts
with io.StringIO() as csvfile:
fieldnames = ['id', 'col1', 'col2', 'col3']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
print(csvfile.getvalue())
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module