gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:25:04 25 4
gpt4 key购买 nike

我有一个这样的字典列表:

[{"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('"') 来解决这个问题。但我无法解决问题。

最佳答案

如果您真的需要它作为 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)

关于python - 将具有不同大小和不同键的字典列表写入 csv 文件并读回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45833644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com