首页 > 解决方案 > 遍历python中的字典值(.values()中的.keys()?)

问题描述

在编程课程中,我现在在 python 中的字典点。所以我有这个任务,我需要添加一个“失败”命令,如果成绩低于 4,它基本上是打印出学生。我已经用谷歌搜索了它并在这里搜索了类似的问题,但就是找不到类似的例子。希望您能够帮助我。另外,我已经添加了代码,并且在“def fail():”中你可以看到我的想法。但是有一个错误代码 - ValueError: too many values to unpack (expected 2)。PS,我是python新手。

students = {('Ozols', 'Jānis'): {'Math': '10', 'ProgVal': '5', 'Sports': '5'},
        ('Krumiņa', 'Ilze'): {'Math': '7', 'ProgVal': '3', 'Sports': '6'},
        ('Liepa', 'Peteris'): {'Math': '3', 'ProgVal': '7', 'Sports': '7'},
        ('Lapsa', 'Maris'): {'Math': '10', 'ProgVal': '10', 'Sports': '3'}}

courses = ['Math', 'ProgVal', 'Sports']


def fail():
for lName, fName in students.keys():
    for course, grade in students.values():
        if grade < 4:
            print(fName, lName)


while True:
print()
command = input("command:> ")
command = command.lower()

if command == 'fail':
    fail()
elif command == 'done':
    break
print("DONE")

标签: pythondictionary

解决方案


试试下面的

students = {
    ('Ozols', 'Jānis'): {
        'Math': '10',
        'ProgVal': '5',
        'Sports': '5'
    },
    ('Krumiņa', 'Ilze'): {
        'Math': '7',
        'ProgVal': '3',
        'Sports': '6'
    },
    ('Liepa', 'Peteris'): {
        'Math': '3',
        'ProgVal': '7',
        'Sports': '7'
    },
    ('Lapsa', 'Maris'): {
        'Math': '10',
        'ProgVal': '10',
        'Sports': '3'
    }
}

courses = ['Math', 'ProgVal', 'Sports']


def fail():
    for k,v in students.items():
        for course, grade in v.items():
            if int(grade) < 4:
              print(f'{k[0]} {k[1]} failed in {course}')

fail()

输出

Krumiņa Ilze failed in ProgVal
Liepa Peteris failed in Math
Lapsa Maris failed in Sports

推荐阅读