简体   繁体   中英

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM