[英]Search within a dictionary with a lot of values in python
在下面的代码中,我展示了一个函数,该函数可以让您将学生添加到以rut为键的字典(书)中,而我遇到的问题是我试图创建一个可以按部门搜索然后打印所有内容的函数该部门的学生是该系的一部分,基本上,我想问的是,如何使用与很多值相关联的1个键来搜索字典,并且您想搜索特定值,然后打印所有带有该键的键他们的信息?
book = {}
def add(rut, name, age, department):
student = {}
student['rut'] = rut
student['name'] = name
student['age'] = age
student['department'] = department
book[rut] = student
def printall():
for rut in book:
student = book[rut]
print(student['rut'], student['name'], student['age'], student['department'])
def main():
count = 0
x = 0
y = int(input("How many students will you add?: "))
while count < y:
print('Input data of the student: ', count+1)
rut = input("rut: ")
name = input("name: ")
age = int(input("age: "))
print("Department 1: RH, 2: Logistic, 3: Cleaners, 4: TI ")
department = ''
while x == 0:
num_dept = int(input("department number: "))
if num_dept == 1:
department = "RH"
x = 1
elif num_dept == 2:
department = "Logistic"
x = 1
elif num_dept == 3:
department = "Mathematics"
x = 1
elif num_dept == 4:
department = "TI"
x = 1
else:
print('Error')
x = 0
add(rut, name, age, department)
count = count + 1
printall()
main()
您可以使用列表推导 。
students = [student for student in book.values()
if student["department"] == desired_department]
这将为您提供一个列表,如果您愿意,可以将其打印出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.