python:检查变量是否已定义并返回其值或返回其他值
我正在尝试使用此代码
result = arr['key1'] or arr['key2'] or arr['key3']
解释: 我希望从 dict 键或 dict 键获得结果的价值..键的可用性取决于环境。这不是关于 None .. 可能只定义了 arr 键之一...
那么是否有像 is_define() 这样的函数或方法
我们如何在 python 中执行此操作?
更新
我在这里遇到了一个新问题.. 代码 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)
代码 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)
请参阅 serverInfo_D[val['name']] & 中的差异serverInfo_D.get(val['名称']) 代码 2 失败,但代码 1 有效,
数据异常。并且 for 循环中迭代 val 的所有代码
serverInfo_D:{'user': 'usr', 'pass': 'pass'}
data: {'par1': 9995, 'extraparam1': 22}
val: {'par1','user','pass','extraparam1'}
为 for data dict 引发
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)