Reputation: 21
I am having difficulty to create nested dictionary from the below mentioned list:
student = ['Mike','Frank']
Type = ['Midterm1','Midterm2','Final']
Scores = [[10,20,30],[40,50,60]]
I am looking for following dictionary:
Scorecard = {'Mike':'Midterm':10,'Midterm2':20,'Final':30},'Frank':
{'Midterm':40,'Midterm2':50,'Final':60}}
I was able to create student and type combination but having difficultly to nest the type and values at the student level.
The output would be
scorecard['Mike']['Midterm'] = 10
['Mike']['Midterm2'] = 20
Upvotes: 2
Views: 1309
Reputation: 95948
Here's a succinct one-liner:
In [4]: dict(zip(student, (dict(zip(Type, score)) for score in Scores)))
Out[4]:
{'Frank': {'Final': 60, 'Midterm1': 40, 'Midterm2': 50},
'Mike': {'Final': 30, 'Midterm1': 10, 'Midterm2': 20}}
Here it is with the looping a bit more explicit:
In [5]: scorecard = {}
In [6]: for st, score in zip(student, Scores):
...: scorecard[st] = dict(zip(Type,score))
...:
...:
In [7]: scorecard
Out[7]:
{'Frank': {'Final': 60, 'Midterm1': 40, 'Midterm2': 50},
'Mike': {'Final': 30, 'Midterm1': 10, 'Midterm2': 20}}
Upvotes: 3