Reputation: 591
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.
Upvotes: 2
Views: 1910
Reputation: 1592
If you really need this as a CSV file, I think your issue is where you create temp_list
your're creating a nested list when you append to it.
Try this instead:
# use meaningful names
dictionary_list = [{"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 d in dictionary_list:
temp_list=[]
for key,value in d.items():
# notice the difference here, instead of appending a nested list
# we just append the key and value
# this will make temp_list something like: [a0, 0, a1, 1, etc...]
temp_list.append(key)
temp_list.append(value)
file_temp_writer.writerow(temp_list)
Upvotes: 3
Reputation: 42746
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)
Upvotes: 2