我有一个实例,我想比较嵌套在另一本词典中的字典之间的数据。嵌套字典都具有相同的格式;看起来像这样:
students = {"student_1": {"id":1009, "first_name": "Alex", "last_name": "Robertson",
"Assignments":[("Assignment_1",3),("Assignment_2", 4),
("Assignment_3", 2), ("Assignment_4", 4)]},
"student_2" :{"id":2009, "first_name": "Dave", "last_name": "Davidson",
"Assignments":[("Assignment_1",2),("Assignment_2", 1),
("Assignment_3", 2), ("Assignment_4", 4)]},
"student_3" :{"id":3009, "first_name": "Hayden", "last_name": "Miles",
"Assignments":[("Assignment_1",1),("Assignment_2", 1),
("Assignment_3", 1), ("Assignment_4", 1)]},
"student_4" :{"id":4009, "first_name": "Randy", "last_name": "Bacon",
"Assignments":[("Assignment_1",2),("Assignment_2", 2),
("Assignment_3", 2), ("Assignment_4", 4)]},
"student_5" :{"id":5009, "first_name": "Katrina", "last_name": "Lopez",
"Assignments":[("Assignment_1",2),("Assignment_2", 1),
("Assignment_3", 2), ("Assignment_4", 3)]},
"student_6" :{"id":6009, "first_name": "Tessa", "last_name": "Franklin",
"Assignments":[("Assignment_1",1),("Assignment_2", 4),
("Assignment_3", 2), ("Assignment_4", 4)]}}
我想做的是指定一个特定的作业(元组中的字符串),并抽出与该作业相关的所有六个年级,并将其与学生的ID号配对。例如,如果我要为Assignment_1评分,则结果将是一个具有ID和Assignment_1中的评分的元组列表,或者是student_#的有序列表。非常感谢您的帮助,这就是我一直在尝试使用的方法:
def highest_n_grades(dict, tuple, int):
save_data = []
for d in dict:
for k in d:
if k == "Assignments":
if [0] == tuple:
data = d["id"],d["first_name"],d["last_name"],k[1]
save_data.append(data)
return save_data
代码会运行,但只会返回空括号。
答案 0 :(得分:0)
您的if语句将始终为False,因为您正在将具有一个值的列表与字符串进行比较。
您可以这样尝试(假设“ tuple”是一个字符串):
search_assignment = "Assignment_1"
def highest_n_grades(students, search_assignment):
save_data = []
for student in students:
student_data = students[student]
assignments = student_data["Assignments"]
for assignment in assignments:
if assignment[0] is search_assignment:
data = (student_data["id"], student_data["first_name"], student_data["last_name"], assignment[1])
save_data.append(data)
答案 1 :(得分:0)
为了我的理解,我对您的代码做了一些修改。该代码提取给定作业的学生成绩。
def highest_n_grades(dict, tuple):
save_data = []
for d_id,d_info in dict.items():
assignments = d_info['Assignments']
for el in assignments:
if el[0] == tuple:
data = d_info["id"],d_info["first_name"],d_info["last_name"],el[1]
save_data.append(data)
return save_data
用例:
highest_n_grades(students,'Assignment_1')
[(1009, 'Alex', 'Robertson', 3),
(2009, 'Dave', 'Davidson', 2),
(3009, 'Hayden', 'Miles', 1),
(4009, 'Randy', 'Bacon', 2),
(5009, 'Katrina', 'Lopez', 2),
(6009, 'Tessa', 'Franklin', 1)]