开发者

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 d开发者_JS百科ata dict .. and all code in for loop which iterates over val


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜