我有 2 csv
文件(分号分隔)具有以下结构和示例数据:
文件 1:
qid;question
1.0;How can I find specific content
2.0;How do I modify content
2.0;How can I edit items
2.0;I need to change some answers
3.0;How do I troubleshoot and fix problems
文件 2:
qid;answer
1.0;Use the Filter feature to filter the items
2.0;Use the test tool to find your existing documents and edit them
3.0;Use the test tool to test a document
现在我想做的是形成一个 JSON
包含来自两个文档的数据的结构,形成以下示例结构:
{
"qna": [
{
"qid": "1.0",
"q": [
"How can I find specific content"
],
"a": "Use the Filter feature to filter the items."
},
{
"qid": "2.0",
"q": [
"How do I modify content","How do I edit items","I need to change some answers"
],
"a": "Use the test tool to find your existing documents and edit them."
},
{
"qid": "3.0",
"q": [
"How do I troubleshoot and fix problems"
],
"a": "Use the test tool to test a document"
}
]
}
正如你所看到的 JSON
包含 list of list
qna
内 field 。此 list of list
中的每一项包含qid
,匹配相同的问题列表 qid
,并且答案匹配 qid
.
我在阅读这些 2 csv
时编写了这段代码文件和成型2 list of lists
:
qid_question_list = {}
qid_answer_list = {}
reader1 = csv.reader(csv_file1, delimiter=';')
next(reader1)
reader2 = csv.reader(csv_file2, delimiter=';')
next(reader2)
for qid,question in reader1:
if qid not in qid_question_list:
qid_question_list[qid] = list()
qid_question_list[qid].append(question)
for qid,answer in reader2:
if qid not in qid_answer_list:
qid_answer_list[qid] = list()
qid_answer_list[qid].append(answer)
当我执行上面的命令时,我得到以下 2 lists
:
qid_question_list
{'1.0': ['How can I find specific content'], '2.0': ['How do I modify content','How do I edit items','I need to change some answers'], '3.0': ['How do I troubleshoot and fix problems']}
qid_answer_list
{'1.0': ['Use the Filter feature to filter the items'], '2.0': ['Use the test tool to find your existing documents and edit them'], '3.0': ['Use the test tool to test a document']}
现在我无法确定如何组合这 2 list of lists
形成所需的JSON
结构如上所示?
最佳答案
假设你手头有这两个字典
l1={'1.0': ['How can I find specific content'], '2.0': ['How do I modify content','How do I edit items','I need to change some answers'], '3.0': ['How do I troubleshoot and fix problems']}
l2={'1.0': ['Use the Filter feature to filter the items'], '2.0': ['Use the test tool to find your existing documents and edit them'], '3.0': ['Use the test tool to test a document']}
l = [ {"qid": k, "q": v, "a": l2[k]} for k,v in l1.items() ]
q={'qna': l }
print(q)
输出
{'qna': [{'qid': '1.0', 'q': ['How can I find specific content'], 'a': ['Use the Filter feature to filter the items']}, {'qid': '2.0', 'q': ['How do I modify content', 'How do I edit items', 'I need to change some answers'], 'a': ['Use the test tool to find your existing documents and edit them']}, {'qid': '3.0', 'q': ['How do I troubleshoot and fix problems'], 'a': ['Use the test tool to test a document']}]}
关于python - 如何在 python 中组合 2 个列表中的数据以形成单个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47337948/