简体   繁体   English

通过遍历列表中的值来获取字典值 | Python

[英]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我想做一个 function search_subject来搜索一个主题并找到该主题的相应教授,例如{professor1: [biology, maths], professor2: [gymnastics, arts]如果你在被要求输入时输入biology ,你会得到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.items()并检查主题

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 Output: professor1 1

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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