2 回答
TA贡献1946条经验 获得超4个赞
我通过在写作方面处理事情来解决这个问题。将我的问题传递到 CSV 中时,我正在用我的嵌套对象创建一个字典。从 CSV 读取时,这会引起头痛。所以现在我使用这一行来修复我的嵌套对象:
question = {key: (json.dumps(value) if key in ['question', etc. etc.] else value) for key, value in question.items()}TA贡献1772条经验 获得超8个赞
您可以使用此函数将 csv 读入具有列的字典列表:值结构:
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": []
}
]
添加回答
举报
