Python 将具有不同大小和不同键的词典列表写入csv文件并读回
我有一个这样的字典列表:Python 将具有不同大小和不同键的词典列表写入csv文件并读回,python,dictionary,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_wr
[{"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)
现在,如果我打印(B),结果将是:
[{'[': '['}, {'[': '['}, {'[': '['}]
我知道问题是,当我在csv文件中写入时,它会将每个元素保存为字符串。例如,
“[['a0'],[0]]”
而不是[['a0'],[0]]
。我使用了strip(“”)
来解决这个问题。但我无法解决这个问题。要保存字典,使用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)
要再次检索数据,请执行以下操作:
with open("file_temp.json", "r") as f:
B = json.load(f)
如果您真的需要将其作为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)
它是否依赖于csv?或者是否可以使用json等其他格式?您应该只使用
json
。我不知道json。但我认为它不一定是csv文件。