PMA*_*INA 1 python dictionary nested
所以如果我能够嵌套字典,我的代码看起来最好.我的问题是:
以下是我尝试使用的一些代码.请告诉我正确的格式是什么,以及可能出错的地方......谢谢!
Student.Alice = {
Student.Alice.Math = {
'math1'= 100
'math2'= 98
'math3' = 89
'math4' = 91
'math5' = 77
'math6' = 90
'math7' = 82
'math8' = 100
'math9' = 79
'math10' = 100
}
Student.Alice.English = {
'english1' = 100
'english2' = 97
'english3' = 98
'english4' = 88
'english5' = 94
'english6' = 95
'english7' = 98
'english8' = 82
'english9' = 84
'english10' = 99
}
Student.Alice.Science = {
'science1' = 78
'science2' = 89
'science3' = 88
'science4' = 92
'science5' = 92
'science6' = 91
'science7' = 93
'science8' = 88
'science9' = 99
'science10' = 87
}
Student.Alice.French = {
'french1' = 100
'french2' = 100
'french3' = 99
'french4' = 104
'french5' = 103
'french6' = 97
'french7' = 94
'french8' = 93
'french9' = 75
'french10' = 93
}
}
Run Code Online (Sandbox Code Playgroud)
1,2)是的,嵌套字典是可能的.
d = {'a': 3, 'b': 5}
e = {'a': 4, 'b': 7}
f = {'foo': d, 'bar': e}
Run Code Online (Sandbox Code Playgroud)
3)您可以通过访问子字典元素
print f['bar']['a']
Run Code Online (Sandbox Code Playgroud)
哪个会输出 4
因此,在您的示例中,您可以拥有一个名为学生的词典,其中每个学生都有一个主题词典,每个主题都有一个成绩列表.就像是
students = {
'Alice': {
'Maths': [1, 56, 23, 56],
'Science': [23, 53, 43],
...
},
'Bob': {
'Maths': [1, 56, 23, 56],
'Science': [23, 53, 43],
...
},
...
}
Run Code Online (Sandbox Code Playgroud)
要获得Bob的第二个数学成绩,你会使用students['Bob']['Maths'][1](不要忘记列表项开始索引为0).