Eduard Daduya Eduard Daduya - 2 months ago 7
Python Question

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

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
.

The reason I mentioned
flask
and
flask_restful
is to justify the initialization of
Keys
with
None
values within my dictionary.

Answer

Just use dict.get method with optional default parameter. It returns d[key] if key exists in the dictionary d and default value otherwise:

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