Kair0
Kair0

Reputation: 135

Python : more efficient way to do for this

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

Upvotes: 0

Views: 49

Answers (2)

AKX
AKX

Reputation: 168957

Put your possible values in a dict and use .get() to get one of them (or a default if not found):

bu_lists = {
    'apple': bu_list_apple,
    'banana': bu_list_banana,
    'pear': bu_list_pear,
}
bu_list = bu_lists.get(societe_var, bu_list_cherry)

Upvotes: 2

rdas
rdas

Reputation: 21275

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

Upvotes: 6

Related Questions