如何使用嵌套 *Nested Dictionaries*

How to use nested *Nested Dictionaries*

因此,如果我能够嵌套字典,我的代码将看起来最简洁。 我的问题是:

  1. 嵌套字典是真的吗? (甚至可能吗?)
  2. 如何设置它们?
  3. 如何获取子字典键的值?

这是我尝试使用的一些代码。请告诉我正确的格式是什么,可能有什么错误...谢谢!

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 开始索引)。

您可以使用 dict 将字符串作为键,将 dicts 作为值:

students = {"Alice": {"Math": [100, 98, 70], "English": [100, 97, 98]}}

然后你像这样使用它:students["Alice"]["English"][2] - Alice 在第三次英语测试中的成绩。

可能是这样的:

students = {"Alice": {"Math":    [100, 98, 89, 91, 77, 90, 82, 100, 79, 100],
                      "English": [100, 97, 98, 88, 94, 95, 98, 82, 84, 99],
                      "Science": [78, 89, 88, 92, 92, 91, 93, 88, 99, 87],
                      "French":  [100, 100, 99, 104, 103, 97, 94, 93, 75, 93]
                      }
           }

这里,students是一个字典,字典的键是学生的名字(这里只显示Alice,但你可以添加更多)。每个学生都是一本字典,其关键字是他或她注册的科目。主题是分数列表。也就是说,与其使用带有诸如 french3 之类的键的字典,这些键是多余的,因为我们已经知道它们是法语的分数,并且我们已经知道它是第 #3 项,因为它是第三项,我们只是简单地把它们都按顺序排列在一个列表中,它们的顺序决定了访问它们的索引。 (Python 列表项编号从 0 开始,与原始编号略有不同,但如果要显示编号从 1 开始,可以直接调整它们。)

现在要计算爱丽丝的数学总分,您可以这样写:

sum(students["Alice"]["Math"])

或查看 Alice 的所有分数:

print students["Alice"]

或者看看爱丽丝的第三个法语成绩:

print students["Alice"]["French"][2]

请注意:外部字典最好使用 students 以外的名称,因为这实际上是 分数的集合。学生和学科水平就在那里,所以你可以指定你想要的分数!所以 scores 或者 student_scores 会是一个更好的名字。

嵌套字典,未来必将走向痛苦的世界。我强烈建议学习面向对象编程和 classes。下面是一个不工作但朝着正确方向前进的例子。

class Assignment(dict):
    '''This inherits from a dict, student will be the key, grade as the score'''
    def __init__(self, name, max_score):
        self.name = name
        self.max_score = max_score
        self.grades = {} # this will be used to store students and grades.

    def __getitem__(self, student):
        # we're overriding getitem, because the default is 0 if a student doesn't turn in their work
        if student in self:
            return dict.__getitem__(self, student)
        return 0.0

class GradeBook(dict):
    '''A gradebook is a dict of assignments'''
    def get_max_score(self):
        return sum(assignment.max_score for assignment in self.values())

    def get_percentage(self, student):
        return 100.0 * sum(assignment[student] for assignment in self.values()) / self.get_max_score()

class Course(object):
    def __init__(self, name, time, teacher, students):
        self.name = name
        self.time = time # can teach multiple courses with the same name, but not at the same time
        self.teacher = teacher
        self.students = students
        self.grade_book = GradeBook()

    def add_assignment(self, assignemnt):
        self.grade_book.append(assignment)

class Person(object):
    def __init__(self, first, last):
        self.first = first
        self.last = last
    def __repr__(self):
        return '<{} {} {}>'.format(self.__class__.__name__, self.first, self.last)


class Student(Person):
    '''A student is a person...'''


class Teacher(Person):
    '''A teacher is a person...'''