2016-09-21 61 views
0

一个字典列表我有一个列表的字典,像这样:迭代只多单字典

edu_options = { 'Completed Graduate School' : ['medical','litigation','specialist'...], 

      'Completed College' : ['linguistic','lpn','liberal','chicano'... ], 

      'Attended College' : ['general','inprogress','courseworktowards','continu'...], 

我原来的代码,而在分级匹配的尝试:

for edu_level in edu_options: 
     for option in edu_options[edu_level] 

       if option in cleaned_string: 
         user = edu_level 
         return user 
        else: continue 

我一个比较字符串到这些列表并返回密钥。我想以分层的方式来做。

for edu_level in edu_options: 
     for option in edu_options[edu_level]: 

      if cleaned_string in edu_options["Completed Graduate School"]: 
        user = "Completed Graduate School" 
        return user        

      elif cleaned_string in edu_options["Completed College"]: 
        user = "Completed College" 
        return user 

      elif option in cleaned_string: 
        user = edu_level 
        return user 

这些if语句适用于大多数比较str,但不会拿起几个例子。对于第一个和第二个if语句,我只想将其与“完成的研究生院”等相应列表进行比较。有没有办法迭代通过只有该列表而不使用另一个for循环?类似于

Ex: string = Bachelor of Arts: Communication and Civil Service 
    cleaned_string = bachelorofartscommunicationandcivilservice 
    option = iterating through each item(str) of lists in edu_option 

我想让毕业生和大学名单首先通过,因为他们更小,更具体。我想纠正的错误是edu_options中的另一个更大的列表,其中包含与str_string_string不匹配的子str。

+0

清单字符串是一个列表吗?或者你正在查找cleanded_string中的子字符串? –

+0

cleared_string只是一个str,我想与ers_options列表中的strs比较 – pproctor

+0

所以,当你说“elif option in cleaned_string”时,这个选项是一个字符串,它将在clean_string里查找(这也是一个字符串)。这是你打算做什么? –

回答

1

如何:

for key, val_list in edu_options.items(): 
    if key == "Completed Graduate School": 
     if cleaned_string in val_list: 
      #do something 
    #Similarly for remaining key types 

这样一来,您被限制检查专门的密钥类型。

0
for edu_level in edu_options: 
     for option in edu_options[edu_level]: 

      if cleaned_string in edu_options["Completed Graduate School"]: 
        user = "Completed Graduate School" 
        return user        

      elif cleaned_string in edu_options["Completed College"]: 
        user = "Completed College" 
        return user 

      elif option == cleaned_string: 
        user = edu_level 
        return user