我是Python的新手(我已经学习了大约一个星期,但我知道R)。
我正在尝试创建一个嵌套字典,将学生的名字映射到包含他们分数的字典。这个分数字典的每个条目都应该以作业名称为关键字,并将相应的分数保存为整数。例如,grade_dicts['荆棘']['考试1']== 100
我很接近,但是在def Convert函数中有一些东西我没有正确地做,我想知道你是否可以提供一些帮助。我读过嵌套字典:https://www.geeksforgeeks.org/python-nested-dictionary/,但这个问题似乎根本不同,因为它来自一个元组。
谢谢!
grades = [
# First line is descriptive header. Subsequent lines hold data
['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
['Thorny', '100', '90', '80'],
['Mac', '88', '99', '111'],
['Farva', '45', '56', '67'],
['Rabbit', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Foster', '89', '97', '101']
]
def assign(grades):
assignments = []
for i in grades[:]:
assignments.extend(i[:]) #play around with this! #ended up using extend
return(assignments)
assignments = assign(grades)
assignments = list(zip(*[iter(assignments)]*4))
assignments = assignments[1:7]
def Convert(tup, di):
for a, b,c,d in tup:
di.setdefault(a, [])
di.setdefault(b, ['Exam 1'])
di.setdefault(c, ['Exam 2'])
di.setdefault(d, ['Exam 3'])
return di
dictionary = {}
grade_lists = Convert(assignments, dictionary)
grade_lists
您可以使用嵌套字典推导来构建您的输出,首先将初始数据转换为更简单的格式,例如:
grades = [
# First line is descriptive header. Subsequent lines hold data
['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
['Thorny', '100', '90', '80'],
['Mac', '88', '99', '111'],
['Farva', '45', '56', '67'],
['Rabbit', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Foster', '89', '97', '101']
]
exams = grades[0][1:]
names = [data[0] for data in grades[1:]]
list_of_values = [data[1:] for data in grades[1:]]
output = {
name: { exam: value for exam,value in zip(exams, values) } for name,values in zip(names, list_of_values)
}
print(output)
>>> {'Thorny': {'Exam 1': '100', 'Exam 2': '90', 'Exam 3': '80'}, 'Mac': {'Exam 1': '88', 'Exam 2': '99', 'Exam 3': '111'}, 'Farva': {'Exam 1': '45', 'Exam 2': '56', 'Exam 3': '67'}, 'Rabbit': {'Exam 1': '59', 'Exam 2': '61', 'Exam 3': '67'}, 'Ursula': {'Exam 1': '73', 'Exam 2': '79', 'Exam 3': '83'}, 'Foster': {'Exam 1': '89', 'Exam 2': '97', 'Exam 3': '101'}}
# example
print(output['Ursula']['Exam 1'])
>>> 73