Create nested dictionary from three (3) separate list different length

I need to create one nested dictionary to describe six (6) students scores for 3 exams;

dd = {

    'T': {'Exam 1': 100, 'Exam 2': 90, 'Exam 3': 80},
    'M': {'Exam 1': 88, 'Exam 2': 99, 'Exam 3': 111},
    'F': {'Exam 1': 45, 'Exam 2': 56, 'Exam 3': 67},
    'R': {'Exam 1': 59, 'Exam 2': 61, 'Exam 3': 67},
    'U': {'Exam 1': 73, 'Exam 2': 79, 'Exam 3': 83},
    'F': {'Exam 1': 89, 'Exam 2': 97, 'Exam 3': 101}
}

Original input and prep are:

import pandas as pd

grades = [

    ['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
    ['T', '100', '90', '80'],
    ['M', '88', '99', '111'],
    ['F', '45', '56', '67'],
    ['R', '59', '61', '67'],
    ['U', '73', '79', '83'],
    ['F', '89', '97', '101']
]

headers = grades.pop(0)
df = pd.DataFrame(grades, columns=headers)

df[['Exam 1','Exam 2','Exam 3']] = df[['Exam 1','Exam 2','Exam 3']].astype(int)

I can create the lists for dictionary creation:

students = df['Student'].tolist()
assignments = list(df.columns.values)
assignments.remove('Student')

Problem:

internal dictionary: keys – assignment (3), values – scores (6) Outer dictionary: keys – students (6), values – assignments (3)

I do not know how to handle the scores list!! It is 6 per assignment but is it a list of lists (3 x 6)??

I would like to use the zip function:

keys = students
values = assignments

result = dict(zip(keys, values))

but I do not know how to iterate internal dictionary:

keys = assignments. (3 elements)
values = scores (has to be 3 by 6) #-  how to iterate it if it is possible at all?

result = dict(zip(keys, values))

Thank you for your help!!

Answer

You can use pandas to_dict function directly on your dataframe. However, your dataframe has duplicate students, so you won’t be able to get your example dictionary exactly (must have unique keys).

Removing the duplicate “F” student for illustration…

import pandas as pd

grades = [

    ['Student', 'Exam 1', 'Exam 2', 'Exam 3'],
    ['T', '100', '90', '80'],
    ['M', '88', '99', '111'],
    ['F', '45', '56', '67'],
    ['R', '59', '61', '67'],
    ['U', '73', '79', '83']
]

headers = grades.pop(0)
df = pd.DataFrame(grades, columns=headers)

df[['Exam 1','Exam 2','Exam 3']] = df[['Exam 1','Exam 2','Exam 3']].astype(int)

df = df.set_index('Student')
dd = df.to_dict(orient='index')
print(dd)

{'T': {'Exam 1': 100, 'Exam 2': 90, 'Exam 3': 80}, 
'M': {'Exam 1': 88, 'Exam 2': 99, 'Exam 3': 111}, 
'F': {'Exam 1': 45, 'Exam 2': 56, 'Exam 3': 67}, 
'R': {'Exam 1': 59, 'Exam 2': 61, 'Exam 3': 67}, 
'U': {'Exam 1': 73, 'Exam 2': 79, 'Exam 3': 83}}