因此,如果我能够嵌套字典,我的代码将看起来最简洁。 我的问题是:
- 嵌套字典是真的吗? (甚至可能吗?)
- 如何设置它们?
- 如何获取子字典键的值?
这是我尝试使用的一些代码。请告诉我正确的格式是什么,可能有什么错误...谢谢!
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
}
}
请您参考如下方法:
1, 2) 是的,嵌套字典是可能的。
d = {'a': 3, 'b': 5}
e = {'a': 4, 'b': 7}
f = {'foo': d, 'bar': e}
3) 您可以通过以下方式访问子字典元素
print f['bar']['a']
这将输出 4
所以在您的示例中,您可以有一个名为学生的字典,其中每个学生都有一个科目字典,每个科目都有一个成绩列表。有点像
students = {
'Alice': {
'Maths': [1, 56, 23, 56],
'Science': [23, 53, 43],
...
},
'Bob': {
'Maths': [1, 56, 23, 56],
'Science': [23, 53, 43],
...
},
...
}
要获得 Bob 的第二个数学成绩,您可以使用 students['Bob']['Maths'][1](不要忘记列表项从 0 开始索引)。
