我最近在python中完成了一项家庭作业,我不得不制作一份假学生ID字典,并将各种作业的相应成绩放入嵌套字典中。带有ID的字典我能够毫无问题地制作,但我似乎无法将相应的成绩放入其中。 文件内容的一个例子是:
807-49-0073
658-30-1272
544-78-7923
709-40-8165
492-42-7987
503-27-1729
840-12-4303
169-09-7157
560-33-3099
278-16-5335
097-26-3512
267-10-7633
979-49-6579
821-67-0672
393-36-5485
然后是他们的ID和成绩的那个:
267-10-7633 66
709-40-8165 71
097-26-3512 78
807-49-0073 83
169-09-7157 73
278-16-5335 79
979-49-6579 79
544-78-7923 85
560-33-3099 73
840-12-4303 62
821-67-0672 87
503-27-1729 8
267-10-7633 85
979-49-6579 60
503-27-1729 62
821-67-0672 62
393-36-5485 15
560-33-3099 38
097-26-3512 80
658-30-1272 85
278-16-5335 84
169-09-7157 70
840-12-4303 73
544-78-7923 60
560-33-3099 87
840-12-4303 75
979-49-6579 96
492-42-7987 85
544-78-7923 72
169-09-7157 82
278-16-5335 67
709-40-8165 96
393-36-5485 87
097-26-3512 85
821-67-0672 86
278-16-5335 97
393-36-5485 73
503-27-1729 78
979-49-6579 24
821-67-0672 87
544-78-7923 73
709-40-8165 34
097-26-3512 73
840-12-4303 100
807-49-0073 75
267-10-7633 74
658-30-1272 94
492-42-7987 87
所以我需要取最后两位数字并将其与相应的学生一起放入。有些人重复了。到目前为止,这是我的代码,但我目前卡住了。
def create_dictionary(idfilename, hwfilename):
hwL = []
dict1 = {}
dict2 = {'hw': hwL}
ids = open(idfilename, 'r').read().splitlines()
hws = open(hwfilename, 'r').read().splitlines()
for i in ids:
dict1[i] = dict1.get(i, dict2)
for k in hws:
hwL = k.split(' ')
答案 0 :(得分:-1)
我现在无法调试,但这应该很接近:
import csv
#assuming the files are .csvs
def create_dictionary(idfilename, hwfilename):
#declare the field names of the dictionaries so we can refer to them later
field_names1 = ['id']
field_names2 = ['id','grade']
dictOf_Ids = csv.DictReader(open(idfilename,fieldnames=field_names1))
dictOf_hw = csv.DictReader(open(hwfilename,fieldnames=field_names2))
#will look something like this: [{'id':'560-33-3099','grades':[76,56,42]}]
listOf_dictionaries =[{}]
#read through the records in the id dictionary line by line
for id in dictOf_Ids:
#each id will have its own list of grades
grades = []
#read through the records in the hw dictionary line by line
for hw in dictOf_hw:
#if the ids match, get the grade from the hw dict and add it to our list of grades for that id
if id.get('id') == hw.get('id'):
grade = hw.get('grade')
grades.append(grade)
else:
#do nothing because the id's don't match
pass
#add the dictionary to the list
dict = {'id':id,'grades':grades}
listOf_dictionaries.append(dict)