Search multiple dictionaries with same keys and different values

时间:2017-04-10 02:08:06

标签: python python-3.x

How do I search these dictionaries and display the multiple values for a certain key (inputted by user)? I want the user to enter the course number they are listed in and output to show room number, instructor, and meeting time.

I cant seem to get my output to display what I want. When I run my programme, I input the course number but the output (ResultList) displays all the courses and times. Instead I want my output to be in the format as in my example. When I enter a course number I want only the information of that course number to be displayed. Right now all the information for all courses are being displayed. HELP please

Please note that the dictionaries must remain in the format I've listed

Code:

list1 = {"CS101":"Room 3004", "CS102":"Room 4501", "CS103":"Room 6755", "NT110":"Room 1244", "CM241":"Room 1411"}

list2 = {"CS101":"Haynes", "CS102":"Alvarado", "CS103":"Rich", "NT110":"Burke", "CM241":"Lee"}

list3 = {"CS101":"08:00", "CS102":"09:00", "CS103":"10:00", "NT110":"11:00", "CM241":"13:00"}

ResultList = {k:[ list1[k], list2[k], list3[k] ] for k in list1}

Course = input("Enter Course Number: \n")

if Course == 'CS101' or 'CS102' or 'CS103' or 'NT110' or 'CM241':
    print(ResultList)
else:
    print("Course not Found!")

Example:

Enter Course Number: 
CS102

CS102
Room 3004
Instructor: Heynes
Meeting time: 08:00

1 个答案:

答案 0 :(得分:0)

Pretty straight forward solution.

>>> Course = "CS102"    
>>> if Course in list1.keys() and list2.keys() and list3.keys():
    ...     print("Room {}\nInstructor: {} \nMeeting time: {}".format(list1[Course], list2[Course], list3[Course]))
    ... else:
    ...     print("Course not found!")
    ... 
    Room Room 4501
    Instructor: Alvarado 
    Meeting time: 09:00

>>> Course = "foo"
>>> if Course in list1.keys() and list2.keys() and list3.keys():
...     print("Room {}\nInstructor: {} \nMeeting time: {}".format(list1[Course], list2[Course], list3[Course]))
... else:
...     print("Course not found!")
... 
Course not found!
>>>