我很难从下面提到的列表中创建嵌套字典:
student = ['Mike','Frank']
Type = ['Midterm1','Midterm2','Final']
Scores = [[10,20,30],[40,50,60]]
我正在寻找以下字典:
Scorecard = {'Mike':'Midterm':10,'Midterm2':20,'Final':30},'Frank':
{'Midterm':40,'Midterm2':50,'Final':60}}
我能够创建学生和类型组合,但难以在学生级别嵌套类型和值。
输出为
scorecard['Mike']['Midterm'] = 10
['Mike']['Midterm2'] = 20
答案 0 :(得分:2)
这是一个简洁的单行:
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}}
这里的循环更明确一点:
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}}