I need to create variables dynamically based on the data that is coming from my UI.
Sample JSON: Some of the sample JSON I'll get from UI to hit the python code.
data_json = {'key1':'value1','key2':'value2','key3':['abc','def']}
data_json = {'key1':'value2','key2':'value8','key3':['abc','def','ghi','jklmn']}
data_json = {'key1':'value3','key2':'value9','key3':['abc']}
data_json = {'key1':'value4','key2':'value2','key3':['abc','def','xyz']}
data_json = {'key1':'value6','key2':'value2','key3':['abc','def']}
I have data in JSON format in which the length of the "key3" value will keep changing each time. I have to capture those values in separate variables and have to use them later in other functions.
If I pass the first data_json first block of if condition will work and assign it to variables. And if I pass the second data_json second block will define the variables.
Python:
secret = data_json['key1']
if secret in ['value1','value6']:
first_value = data_json['key3'][0]
second_value = data_json['key3'][1]
if secret in ['value2']:
first_value = data_json['key3'][0]
second_value = data_json['key3'][1]
third_value = data_json['key3'][2]
fourth_value = data_json]'key3'][3]
if secret in ['value3']:
first_value = data_json['key3'][0]
if secret in ['value4']:
first_value = data_json['key3'][0]
second_value = data_json['key3'][1]
third_value = data_json['key3'][2]
print("Value in first:%s",first_value)
print("Value in second :%s",second_value)
print("Value in third:%s",third_value)
I'm using conditions to capture those variables.The above code is working fine. But I have to avoid using if conditions. Is there any way to define the variables dynamically on the fly and so that i can use it later in same functions?