将具有不同大小和不同键的字典列表写入csv文件并读回

时间:2017-08-23 07:45:41

标签: python dictionary

我有一个像这样的词典列表:

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

我想将其保存到csv文件并将其读回。

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)

现在csv文件是:

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

然后再读回来:

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)

现在,如果我print(B),结果将是:

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

我知道问题是当我在csv文件中写入时,它将每个元素保存为字符串。例如"[['a0'], [0]]"而不是[['a0'], [0]]。我使用strip('"')来解决这个问题。但我无法解决问题。

2 个答案:

答案 0 :(得分:2)

要保存字典,使用sound

很容易
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)

答案 1 :(得分:2)

如果您确实需要将其作为CSV文件,我认为您的问题是在创建temp_list时创建嵌套列表的位置。

请改为尝试:

# 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)