James
James

Reputation: 589

Creating a Nested Dictionary While Converting to a Tuple

I'm new to Python (I've been learning for roughly a week, but I know R).

I'm trying to create a nested dictionary that maps names of students to dictionaries containing their scores. Each entry of this scores dictionary should be keyed on assignment name and hold the corresponding grade as an integer. For instance, grade_dicts['Thorny']['Exam 1'] == 100

I'm close, but there's something within the def Convert function that I'm not doing correctly, and I'm wondering if you could offer some help. I've read about nested dictionaries: https://www.geeksforgeeks.org/python-nested-dictionary/ but this issue seems fundamentally different given how it's coming from a tuple.

Thanks much!

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

Upvotes: 0

Views: 1058

Answers (1)

marcos
marcos

Reputation: 4510

You can do nested dictionary comprehension to build your output, first transform the initial data into an easier format, for example:

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

Upvotes: 1

Related Questions