2017-02-19 2 views
0

Мне удалось преобразовать 3 текстовых файла в список в словарь, но теперь я должен поместить эти 3 словаря в супер-словарь со следующей структурой.Словарь с 3 словарями в нем

"123-45-6789": {"hw": [98,89,92,75], "quiz": [45,36,42,50,29,27,40,41], " экзамен ": [175157]}

я сделал словарь по умолчанию со всеми studentids, что все не имеет значения и у меня есть три словарей называемых examList, hwList и quizList, которые имеют следующую структуру (длину значений изменяются)

{ '709-40-8165': [168, 98], '560-33-3099': [176, 16]}

поэтому вопрос, как я могу перебрать словарь studentid по умолчанию добавить следующие словари?

Вот некоторые из кода

fullRoster= dict() 
    idList= [] 
    quizList= [] 
    hwList= [] 
    examList= [] 
    studentids= open("studentids.txt", "r") 
    idList= [line.rstrip()for line in studentids] 
    studentids.close() 
    idList= dict.fromkeys(idList) 
    #hwFile converted into a list and then into a dictionary 
    #the exam and homework files follow the same structure 
    hwFile= open("hwscores.txt", "r") 
    hwList= [line.rstrip().split() for line in hwFile] 
    hwFile.close() 
    #searches for similar ids then places quiz score into single list 
    for i in range (15): 
     for k in range ((len(hwList))): 
      if hwList[i][0]== hwList[k][0] and i!=k: 
       hwList[i].append((hwList[k][1])) 
    hwList= hwList[:15] 
    #adds zero if hw list is not 5 
    for i in range (15): 
     if len(hwList[i])!=5: 
      while len(hwList[i])<5: 
       hwList[i].append(0) 
    #dictionary comprehension to create dictionary 
    hwList= {l[0]: [int(x) for x in l[1:]] for l in hwList} 
+1

Ваша проблема будет лучше проиллюстрирована, если вы можете показать код и указать этот код, чтобы объяснить, что происходит с вашей проблемой. Это позволит читателям также быстрее и лучше понимать, как вам помочь. – idjaw

+0

@ только только что отредактирован –

ответ

0

Я бы подойти к нему так:

# Example exam, hw, and quiz score dicts: 
examList = {'709-40-8165': [168, 98], '560-33-3099': [176, 16]} 
hwList = {'709-40-8165': [15, 10], '602-33-3099': [17, 5]} 
quizList = {'709-40-8165': [15, 10]} 

# Add scores for that student ID 
def add_scores(superList, scoreList, scoreType): 
    for studentID,value in scoreList.items(): 
     if studentID not in superList.keys(): 
      superList[studentID] = {} 
     superList[studentID][scoreType] = value 

superList = {} 
add_scores(superList, examList, 'exam') 
add_scores(superList, quizList, 'quiz') 
add_scores(superList, hwList, 'hw') 

print(superList)    

Это дает:

{'602-33-3099': {'hw': [17, 5]}, '709-40-8165': {'exam': [168, 98], 'hw': [15, 10], 'quiz': [15, 10]}, '560-33-3099': {'exam': [176, 16]}} 

Он перебирает каждый dict и добавляет в баллы для этого студенческого удостоверения личности.

0

Следующий код подробно описывает ответ от Brian.

Функция копирует записи студента, поэтому она всегда возвращает копию переданных в нее записей, если таковая имеется, в противном случае она возвращает новый словарь.

import copy 

def add_scores(scores, description, records=None): 
    """Add scores to student records. 

    Use this function to add scores for multiple different 
    kinds of graded exercises in the following way: 

    >>> exam_scores = {'709-40-8165': [168, 98], '560-33-3099': [176, 16]} 
    >>> hw_scores = {'709-40-8165': [15, 10], '602-33-3099': [17, 5]} 
    >>> quiz_scores = {'709-40-8165': [15, 10]} 
    >>> records = add_scores(exam_scores, 'exam') 
    >>> records = add_scores(quiz_scores, 'quiz', records) 
    >>> records = add_scores(hw_scores, 'hw', records) 
    >>> records == {'560-33-3099': {'exam': [176, 16]}, \ 
        '602-33-3099': {'hw': [17, 5]}, \ 
        '709-40-8165': {'exam': [168, 98], \ 
            'hw': [15, 10], \ 
            'quiz': [15, 10]}} 
    True 

    Parameters 
    ---------- 
    scores : dict 
     each key is a student id 
     each value is a list of scores 
    description : str 
     describes the type of score being added 
    records : dict 
     each key is a student id 
     each value is a dictionary of 
     {description: scores} 

    Returns 
    ------- 
    records : dict 
     student records in the format described above 
    """ 
    records = copy.deepcopy(records) if records else {} 
    for student_id, student_scores in scores.items(): 
     record = records.setdefault(student_id, {}) 
     record[description] = \ 
       record.get(description, []) + student_scores 
    return records 
Смежные вопросы