如何检查该值是否在dict列表中

2024-10-01 15:44:28 发布

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

我在学生数据文件中工作,我看到最好的结构如下面的示例所示-如果我错了请纠正我-这是一个字典集合列表,最后一个键有一个字典列表

data = [
{'student_name': 'Khaled ', 'student_id': '19190', 'student_major': 'CS', 'course': [{'course_code': 'PE101', 'course_name': 'Physical Education', 'course_credit': '1', 'course_grade': 'D+'}, {'course_code': 'MATH101', 'course_name': 'Calculus I', 'course_credit': '4', 'course_grade': 'D'}, {'course_code': 'PHYS101', 'course_name': 'Physics I', 'course_credit': '4', 'course_grade': 'F'}, {'course_code': 'CHEM101', 'course_name': 'Chemistry I', 'course_credit': '4', 'course_grade': 'A+\n'}]}, {'student_name': 'Rashed', 'student_id': '18730', 'student_major': 'MIS', 'course': [{'course_code': 'PHYS101', 'course_name': 'Physics I', 'course_credit': '4', 'course_grade': 'D+\n'}]} ]

我希望它可读

我的问题是为什么这个代码不检查我输入的id是否正确

    ID = int(input("Enter you Id : "))

    for student in data: 
        if ID in student: 
            print("the ID is there")
            
        else:
            print("nothing")

以后谢谢你。如果你建议修改文件,请告诉我。我只需要对每个元素进行完全控制,因为我的程序还有许多其他功能


Tags: nameinid列表data字典codestudent
2条回答

在Python中,in运算符检查列表中的直接值,或者检查dict中是否存在key,即

123 in [123, 'xyz']

'key' in {'key': 'value'}

将评估为真


在本例中,您希望检查dict中的值,但代码将检查dict中的key

您可以修改代码以检查dict中的值,如下所示

ID = input("Enter you Id : ")

for student in data:
    if ID == student['student_id']: 
        print("the ID is there")
    else:
        print("nothing")

在这里,检查if条件

我正在检查每个学生的student_id值。另外,检查我是否已从input中删除了int,因为'123'不等于123(引号)

My question is why this code doesn't check if the id I entered correctly?

那是因为

if ID in student:

检查ID是否作为存在,您需要检查

使用

if student['student_id'] == ID:

相反

相关问题 更多 >

    热门问题