[英]Most pythonic way of checking if a Key is in a dictionary and Value is not None
I am using flask
and flask_restful
and has something like 我正在使用
flask
和flask_restful
并有类似的东西
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('OptionalArg', type=str, default=None)
self.reqparse.add_argument('OptionalArg2', type=str, default=None)
self.__args = self.reqparse.parse_args()
if 'OptionalArg' in self.__args and self.__args['OptionalArg'] is not None:
# Do something with the OptionalArg only
pass
else:
# Do something with all the arguments that are not None.
pass
Most relevant answer I found. 我找到的最相关的答案。
Though the question was asked a couple of years back, I was wondering if there is a much more pythonic way of checking if a Key
is in a dictionary and Value
is not None
. 尽管几年前就问过这个问题,但我想知道是否还有更多的Python方法来检查
Key
是否在字典中,而Value
是否不是None
。
The reason I mentioned flask
and flask_restful
is to justify the initialization of Keys
with None
values within my dictionary. 我提到
flask
和flask_restful
的原因是为了证明字典中具有None
值的Keys
的初始化是合理的。
Just use dict.get
method with optional default
parameter. 只需将
dict.get
方法与可选的default
参数一起使用即可。 It returns d[key]
if key
exists in the dictionary d
and default
value otherwise: 它返回
d[key]
如果key
存在于字典d
和default
否则值:
In [1]: d = {1: 'A', 2: None}
In [2]: d.get(1)
Out[2]: 'A'
In [3]: d.get(2)
In [4]: d.get(1) is not None
Out[4]: True
In [5]: d.get(2) is not None
Out[5]: False
In [6]: d.get(3) is not None
Out[6]: False
For your case: 对于您的情况:
if self.__args.get('OptionalArg') is not None:
# Do something with the OptionalArg only
pass
else:
# Do something with all the arguments that are not None.
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.