简体   繁体   中英

Get dictionary value by iterating through values on a list | Python

I want make a function search_subject to search for a subject and find the respective professor of the subject eg {professor1: [biology, maths], professor2: [gymnastics, arts] If you enter biology when you are asked for input you get professor1

I'm trying to avoid making a nested dictionary for this project and I'm stuck, any help is appreciated

Loop through professors.items() and check for the subject

professors = {'professor1' : ['biology', 'maths'],  'professor2' : ['gymnastics', 'arts']}

def search_subject(target):
    for key, val in professors.items():
        if target in val:
            return key
    return False

print(search_subject('biology'))

Output: professor1

Remember to quote the strings.
Invert the dictionary.
Use the inverted dictionary to look up professors by subject.

professor_to_subjects = {'professor1' : ['biology', 'maths'],
                         'professor2' : ['gymnastics', 'arts'], }

subject_to_professor = {}

for professor, subjects in professor_to_subjects.items():
    for subject in subjects:
        subject_to_professor[subject] = professor

print(subject_to_professor)
# {'biology': 'professor1', 'maths': 'professor1', 'gymnastics': 'professor2', 'arts': 'professor2'}

print(subject_to_professor['biology'])
# professor1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM