协助嵌套字典
Assistance with Nested Dictionary
所以我的代码应该做的是获取学生 ID 并将它们放入字典,然后将他们的家庭作业、考试和测验成绩也放入字典中。
所以它应该看起来像
{'123456':{'exam':[97, 98, 45], 'homework': [44,45]} etc.
所以为了快速起见,我只添加了一部分以专注于作业部分。我将如何将该家庭作业字典添加到学生 ID 的字典中? (家庭作业文件有学号和成绩)
def create_dictionary(idfilename, hwfilename):
ids = open(idfilename, 'r')
hw = open(hwfilename, 'r')
d = {}
grades = {}
for i in ids:
ids.readline()
i = i.rstrip("\n")
grades[i] = d
for h in hw:
x = hw.readline()
x.split(' ')
if h in grades:
d = [i]
print(grades)
我关闭了吗?
您的问题不清楚,因为您的输入数据的形式未知。但一般来说,您可以执行以下操作:
out_dict = {'123456':{'exam':[97, 98, 45], 'homework': [44,45]}}
# example of a list with grades. maybe read from a file?
homework_grades = [1,2,3,4]
# appends grades one at a time
for a_grade in homework_grades:
out_dict['123456']['homework'].append(a_grade)
# or append all grades in one go.
out_dict['123456']['homework'] += homework_grades
所以我的代码应该做的是获取学生 ID 并将它们放入字典,然后将他们的家庭作业、考试和测验成绩也放入字典中。
所以它应该看起来像
{'123456':{'exam':[97, 98, 45], 'homework': [44,45]} etc.
所以为了快速起见,我只添加了一部分以专注于作业部分。我将如何将该家庭作业字典添加到学生 ID 的字典中? (家庭作业文件有学号和成绩)
def create_dictionary(idfilename, hwfilename):
ids = open(idfilename, 'r')
hw = open(hwfilename, 'r')
d = {}
grades = {}
for i in ids:
ids.readline()
i = i.rstrip("\n")
grades[i] = d
for h in hw:
x = hw.readline()
x.split(' ')
if h in grades:
d = [i]
print(grades)
我关闭了吗?
您的问题不清楚,因为您的输入数据的形式未知。但一般来说,您可以执行以下操作:
out_dict = {'123456':{'exam':[97, 98, 45], 'homework': [44,45]}}
# example of a list with grades. maybe read from a file?
homework_grades = [1,2,3,4]
# appends grades one at a time
for a_grade in homework_grades:
out_dict['123456']['homework'].append(a_grade)
# or append all grades in one go.
out_dict['123456']['homework'] += homework_grades