Using DictWriter to write a CSV when the fields are not known beforehand

2024/9/23 18:19:34

I am parsing a large piece of text into dictionaries, with the end objective of creating a CSV file with the keys as column headers.

csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

The problem arises as the dict for any 'n'th row can include a new, never before used key. I then want the CSV to contain a column for this new key as well. In short, all my fields are not known beforehand so I cannot compile a complete fieldnames at the beginning.

Is there a recommended way to have csv.DictWriter not ignore missing fields but add them to fieldnames instead? Merely changing fieldnames at this point would leave the prior lines with an incorrectly lower number of fields.

Answer

Instead of using DictWriter which can be confusing in your case as dictionaries are not ordered I tried using writerow method of csv. Here is what i did :

"""
a) First took all the keys of dictionary and sorted it, which is not necessary.
b) Created a result list which appends value related the headers which is key of our input dict and if key is not available then .get() will return None. So result list will contain lists for rows data.
c) Wrote header and each row from result list in csv file
"""data_dict = [{ "Header_1":"data_1", "Header_2":"data_2", "Header_3":"data_3"},{ "Header_1":"data_4", "Header_2":"data_5", "Header_3":"data_6"},{ "Header_1":"data_7", "Header_2":"data_8", "Header_3":"data_9", "Header_4":"data_10"},{ "Header_1":"data_11", "Header_3":"data_12"},{ "Header_1":"data_13", "Header_2":"data_14", "Header_3":"data_15"}]"""In the third dict we have extra key, value.In forth we dont have have header_2 were we aspect blank value in our csv file.
"""
process_data = [ [k,v] for _dict in data_dict for k,v in _dict.iteritems() ]           headers = [ i[0] for i in process_data ]
headers = sorted(list(set(headers)))result = []
for _dict in data_dict:row = []for header in headers:row.append(_dict.get(header, None))result.append(row)import csv
with open('demo.csv', 'wb') as csvfile:spamwriter = csv.writer(csvfile, delimiter=';', dialect='excel', quotechar='|', quoting=csv.QUOTE_MINIMAL)spamwriter.writerow(headers)    for r in result:spamwriter.writerow(r)

enter image description here

https://en.xdnf.cn/q/71793.html

Related Q&A

How to Save io.BytesIO pdfrw PDF into Django FileField

What I am trying to do is basically:Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file, name="Some n…

Which python static checker can catch forgotten await problems?

Code: from typing import AsyncIterableimport asyncioasync def agen() -> AsyncIterable[str]:print(agen start)yield 1yield 2async def agenmaker() -> AsyncIterable[str]:print(agenmaker start)return …

Tkinter : Syntax highlighting for Text widget

Can anyone explain how to add syntax highlighting to a Tkinter Text widget ?Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word tkinter in pi…

how to use pkgutils.get_data with csv.reader in python?

I have a python module that has a variety of data files, (a set of csv files representing curves) that need to be loaded at runtime. The csv module works very well # curvefile = "ntc.10k.csv"…

How to make celery retry using the same worker?

Im just starting out with celery in a Django project, and am kinda stuck at this particular problem: Basically, I need to distribute a long-running task to different workers. The task is actually broke…

Make an AJAX call to pass drop down value to the python script

I want to pass the selected value from dropdown which contains names of databases and pass it to the python script in the background which connects to the passed database name. Following is the ajax co…

PyLint 1.0.0 with PyDev + Eclipse: include-ids option no longer allowed, breaks Eclipse integration

As noted in this question: How do I get Pylint message IDs to show up after pylint-1.0.0?pylint 1.0.0 no longer accepts "include-ids" option. (It returns "lint.py: error: no such optio…

Shifting all rows in dask dataframe

In Pandas, there is a method DataFrame.shift(n) which shifts the contents of an array by n rows, relative to the index, similarly to np.roll(a, n). I cant seem to find a way to get a similar behaviour …

Pandas dataframe: omit weekends and days near holidays

I have a Pandas dataframe with a DataTimeIndex and some other columns, similar to this:import pandas as pd import numpy as nprange = pd.date_range(2017-12-01, 2018-01-05, freq=6H) df = pd.DataFrame(ind…

How to dump a boolean matrix in numpy?

I have a graph represented as a numpy boolean array (G.adj.dtype == bool). This is homework in writing my own graph library, so I cant use networkx. I want to dump it to a file so that I can fiddle wit…