You want
if 'errormessage' in kwargs:
print("found it")
To get the value of errormessage
if 'errormessage' in kwargs:
print("errormessage equals " + kwargs.get("errormessage"))
In this way, kwargs
is just another dict
. Your first example, if kwargs['errormessage']
, means "get the value associated with the key "errormessage" in kwargs, and then check its bool value". So if there's no such key, you'll get a KeyError
.
Your second example, if errormessage in kwargs:
, means "if kwargs
contains the element named by "errormessage
", and unless "errormessage
" is the name of a variable, you'll get a NameError
.
I should mention that dictionaries also have a method .get()
which accepts a default parameter (itself defaulting to None
), so that kwargs.get("errormessage")
returns the value if that key exists and None
otherwise (similarly kwargs.get("errormessage", 17)
does what you might think it does). When you don't care about the difference between the key existing and having None
as a value or the key not existing, this can be handy.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…