goutham
goutham

Reputation: 848

python: check if variable is defined and return its value or return other value

I am trying to use this code

result = arr['key1'] or arr['key2'] or arr['key3']

explanation: I want to have value in result from either or dict keys .. the availability of keys depends on the environment. This is not about None .. only one of the arr keys might be defined ...

so is there a function or method like is_defined()

How do we do this in python ??

UPDATE

I'm having a new problem here .. CODE 1:

try:
   urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D.get(val['name'])))
except KeyError:
   print "expected parameter not provided - "+val["name"]+" is missing"
   exit(0)

CODE 2:

try:
   urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D[val['name']]))
except KeyError:
   print "expected parameter not provided - "+val["name"]+" is missing"
   exit(0)

see the diffrence in serverInfo_D[val['name']] & serverInfo_D.get(val['name']) code 2 fails but code 1 works

the data

serverInfo_D:{'user': 'usr', 'pass': 'pass'} 
data: {'par1': 9995, 'extraparam1': 22}
val: {'par1','user','pass','extraparam1'}

exception are raised for for data dict .. and all code in for loop which iterates over val

Upvotes: 0

Views: 886

Answers (1)

keegan3d
keegan3d

Reputation: 11275

result = arr.get('key1', arr.get('key2', arr.get('key3')))

Upvotes: 7

Related Questions