2016-09-21 145 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