如何使用嵌套*嵌套词典*

2024-09-30 08:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 代码字典格式错误mathstudentalicemath1
3条回答

可能是这样的:

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这样的关键字的字典,这些关键字是多余的,因为我们已经知道它们是法语的分数,而且我们已经知道它是第三项,所以我们只需将它们按顺序放在一个列表中,它们的顺序决定了访问它们的索引。(Python列表项编号以0开头,这与原始编号稍有不同,但如果要显示从1开始编号的条目,则应调整它们。)

现在要计算爱丽丝的数学总分,你可以写下:

^{pr2}$

或者看看爱丽丝所有的分数:

print students["Alice"]

或者看看爱丽丝的第三个法语乐谱:

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

请注意:在外部字典中使用students以外的名称可能更好,因为这实际上是一个分数的集合。学生和科目级别就在那里,你可以指定你想要的分数!所以只要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...'''

1,2)是的,可以使用嵌套字典。在

d = {'a': 3, 'b': 5}
e = {'a': 4, 'b': 7}
f = {'foo': d, 'bar': e}

3)您可以通过以下方式访问子字典元素:

^{pr2}$

它将输出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开始索引)。在

相关问题 更多 >

    热门问题