简体   繁体   中英

How do you create nested dictionaries in Python?

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  

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM