Save List of object with heterogenous keys in csv file in python

I need to store list of objects whose number of keys are not fixed in CSV file.

Example :

suppose I have a object

obj1 = { “name”: “abc”, “class” : “10th” }

obje2 = { “name”: “abcd”, “class” : “11th”, “div” : “A” }

So There will be common elements, but I need to store all the elements

My output would be like this :

enter image description here

Answer

Another solution, with pandas:

import pandas as pd

obj1 = {"name": "abc", "class": "10th"}
obj2 = {"name": "abcd", "class": "11th", "div": "A"}

df = pd.DataFrame([obj1, obj2])
print(df)
df.to_csv("data.csv", index=False)

Prints:

   name class  div
0   abc  10th  NaN
1  abcd  11th    A

and saves data.csv (screenshot from LibreOffice):

enter image description here