Search code examples
pythonpython-3.xseleniumdictionaryformat-string

Select dictionary name based on dynamic values in python & selenium


probably a simple solution but i am not able to figure out how to get dictionary values based on dynamic dictionary names.

I have dictionaries for each type of parameter list with names like cparam_dict_1,cparam_dict_2,cparam_dict_3 etc. I have a function find_parameters with variables r_name, r_type, r_num, How do I select the dictionary based on the number provided by r_num so I can extract values from dictionary like cparam_dict_{r_num}[r_type] where r_type is keys(INBOUND_OSB_RESOURCES etc).

It works if I directly add the complete dictionary name -

element = driver.find_element_by_xpath('//table[@id="' + cparam_dict_1[r_type] + '"]//tbody//tr//td//input[@value="' + r_name + '"]')

but it would be helpful if i can select dictionary names based on r_num

cparam_dict_1 = {
    "INBOUND_OSB_RESOURCES": "tbl_ecp_choice-parameter-28808620766985",
    "OUTBOUND_OSB_RESOURCES": "tbl_ecp_choice-parameter-11676168985228",
    "PASSTHROUGH_OSB_RESOURCES": "tbl_ecp_choice-parameter-11676170588702",
    "BPM_BPEL_COMPOSITE_RESOURCES": "tbl_ecp_choice-parameter-54262573455103813"

}

cparam_dict_2 = {
    "INBOUND_OSB_RESOURCES": "tbl_ecp_choice-parameter-28808620778433",
    "OUTBOUND_OSB_RESOURCES": "tbl_ecp_choice-parameter-116761689785625",
    "PASSTHROUGH_OSB_RESOURCES": "tbl_ecp_choice-parameter-11676170586563",
    "BPM_BPEL_COMPOSITE_RESOURCES": "tbl_ecp_choice-parameter-54262573455112907"

}

def find_parameters(r_type,r_name,r_num):
    element = driver.find_element_by_xpath('//table[@id="' + cparam_dict_{r_num}[r_type] + '"]//tbody//tr//td//input[@value="' + r_name + '"]')

Solution

  • You can use globals() for that

    def find_parameters(r_type,r_name,r_num):
        element = driver.find_element_by_xpath('//table[@id="' + globals()[f'cparam_dict_{r_num}'][r_type] + '"]//tbody//tr//td//input[@value="' + r_name + '"]')