pproctor pproctor - 10 months ago 45
Python Question

Iterate only one dict list from multi list dict

I have a dict of lists like so:

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

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

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

My original code without an attempt at hierarchical matching:

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

I'm comparing a string to these lists and returning the key. I want to do it in a hierarchical way.

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

These if statements work for the majority of comparison str but don't pick up a few cases. For the first and second if statement, I only want to compare it to the respective list such as "Completed Graduate School". Is there a way to iterate through only that list without using another for loop? Something like

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

Answer Source

How about this:

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

This way, you are restricting the checks specifically to the key types.