Python : more efficient way to do for this

Advertisements

I’m a beginner in python and i’m wondering if there is a classy way to do this :

if societe_var == 'apple':
    bu_list = bu_list_apple
elif societe_var == 'banana':
    bu_list = bu_list_banana
elif societe_var == 'pear' :
    bu_list = bu_list_pear
else :
    bu_list = bu_list_cherry

Best regards,

Kair0

>Solution :

Use a dictionary:

bu_list_map = {
    'apple': bu_list_apple,
    'banana': bu_list_banana,
    'pear': bu_list_pear
}

bu_list = bu_list_map.get(societe_var, default=bu_list_cherry)

Use the default argument to the .get() method to handle the fallback case

Leave a ReplyCancel reply