2 回答

TA貢獻1946條經(jīng)驗 獲得超4個贊
我通過在寫作方面處理事情來解決這個問題。將我的問題傳遞到 CSV 中時,我正在用我的嵌套對象創(chuàng)建一個字典。從 CSV 讀取時,這會引起頭痛。所以現(xiàn)在我使用這一行來修復(fù)我的嵌套對象:
question = {key: (json.dumps(value) if key in ['question', etc. etc.] else value) for key, value in question.items()}

TA貢獻1772條經(jīng)驗 獲得超8個贊
您可以使用此函數(shù)將 csv 讀入具有列的字典列表:值結(jié)構(gòu):
import csv
def open_csv(path):
'''return a list of dictionaries
'''
with open(path, 'r') as file:
reader = csv.DictReader(file)
# simple way to do the replacements, but do you really need to do this?
return [{k: [] if v == '[]' else v or None
for k, v in dict(row).items()}
for row in reader]
data = open_csv('test.txt')
# output to json because it looks better, null is None
import json
print(json.dumps(data, indent=4))
測試.csv
name,age,hobby,countries
foo,31,,"['123', 'abc']"
bar,60,python programming,[]
輸出:
[
{
"name": "foo",
"age": "31",
"hobby": null,
"countries": "['123', 'abc']"
},
{
"name": "bar",
"age": "60",
"hobby": "python programming",
"countries": []
}
]
添加回答
舉報