gpt4 book ai didi

python - 我将如何为嵌套的 .JSON 树(Python 字典)调整我的 Python 代码以包含多个键?

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:22 27 4
gpt4 key购买 nike

在我当前的代码中,它似乎只考虑了我的主题键的一个值,而应该有更多(您只能在我的 JSON 树中看到经济学,而不是数学)。我已经尝试了几个小时,但无法正常工作。

这是我的样本数据集——我的完整数据集中有更多主题:

ID,Name,Date,Subject,Start,Finish
0,Ladybridge High School,01/11/2019,Maths,05:28,06:45
0,Ladybridge High School,02/11/2019,Maths,05:30,06:45
0,Ladybridge High School,01/11/2019,Economics,11:58,12:40
0,Ladybridge High School,02/11/2019,Economics,11:58,12:40
1,Loreto Sixth Form,01/11/2019,Maths,05:28,06:45
1,Loreto Sixth Form,02/11/2019,Maths,05:30,06:45
1,Loreto Sixth Form,01/11/2019,Economics,11:58,12:40
1,Loreto Sixth Form,02/11/2019,Economics,11:58,12:40

这是我的 Python 代码:

timetable = {"Timetable": []}
with open("C:/Users/kspv914/Downloads/Personal/Project Dawn/Timetable Sample.csv") as f:
csv_data = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)]

name_array = []
for name in [row["Name"] for row in csv_data]:
name_array.append(name)
name_set = set(name_array)

for name in name_set:
timetable["Timetable"].append({"Name": name, "Date": {}})

for row in csv_data:
for entry in timetable["Timetable"]:
if entry["Name"] == row["Name"]:
entry["Date"][row["Date"]] = {}
entry["Date"][row["Date"]][row["Subject"]] = {
"Start": row["Start"],
"Finish": row["Finish"]
}

这是我的 JSON 树: JSON Tree

最佳答案

您正在使日期字典为空,然后添加一个主题。

做这样的事情:

timetable = {"Timetable": []}
with open("a.csv") as f:
csv_data = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)]

name_array = []
for name in [row["Name"] for row in csv_data]:
name_array.append(name)
name_set = set(name_array)

for name in name_set:
timetable["Timetable"].append({"Name": name, "Date": {}})

for row in csv_data:
for entry in timetable["Timetable"]:
if entry["Name"] == row["Name"]:
if row["Date"] not in entry["Date"]:
entry["Date"][row["Date"]] = {}
entry["Date"][row["Date"]][row["Subject"]] = {
"Start": row["Start"],
"Finish": row["Finish"]
}

我刚刚在将 {} 分配给 entry["Date"][row["Date"]] 之前添加了 if 条件

它将给出如下图所示的输出: enter image description here

关于python - 我将如何为嵌套的 .JSON 树(Python 字典)调整我的 Python 代码以包含多个键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975134/

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