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

Time:06-16

I want make a function search_subject to search for a subject and find the respective professor of the subject e.g {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

CodePudding user response:

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

CodePudding user response:

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
  • Related