mahsa mahsa - 1 month ago 9
Python Question

write a list of dictionaries with different sizes and different keys into csv file and read it back

i have a list of dictionaries like this:

[{"a0":0,"a1":1,"a2":2,"a3":3},{"a4":4,"a5":5,"a6":6},{"a7":7,"a8":8}]


i want to save it to a csv file and read it back.

A=[{"a0":0,"a1":1,"a2":2,"a3":3},{"a4":4,"a5":5,"a6":6},{"a7":7,"a8":8}]
with open("file_temp.csv","w+",newline="") as file_temp:
file_temp_writer=csv.writer(file_temp)
for a in A:
temp_list=[]
for key,value in a.items():
temp_list.append([[key],[value]])
file_temp_writer.writerow(temp_list)


now the csv file is:

"[['a0'], [0]]","[['a1'], [1]]","[['a2'], [2]]","[['a3'], [3]]"
"[['a4'], [4]]","[['a5'], [5]]","[['a6'], [6]]"
"[['a7'], [7]]","[['a8'], [8]]"


and then to read it back:

import csv
B=[]
with open("file_temp.csv","r+",newline="") as file_temp:
file_temp_reader= csv.reader(file_temp)
for row in file_temp_reader:
row_dict={}
for i in range(len(row)):
row[i]=row[i].strip('"')
row_dict[row[i][0]]=row[i][1]
B.append(row_dict)


now if i
print(B)
the result will be:

[{'[': '['}, {'[': '['}, {'[': '['}]


i know the problem is that when i write in a csv file, it save each element as a string. for example
"[['a0'], [0]]"
instead of
[['a0'], [0]]
. i used
strip('"')
to solve this problem. but i cant solve the problem.

Answer Source

To save a dictionary it is easy using json:

import json
A=[{"a0":0,"a1":1,"a2":2,"a3":3},{"a4":4,"a5":5,"a6":6},{"a7":7,"a8":8}]
with open("file_temp.json", "w") as f:
    json.dump(A, f)

To retrieve data again:

with open("file_temp.json", "r") as f:
        B = json.load(f)