Python 3.2.3. There were some ideas listed here, which work on regular var’s, but it seems **kwargs play by different rules… so why doesn’t this work and how can I check to see if a key in **kwargs exists?
if kwargs['errormessage']:
print("It exists")
I also think this should work, but it doesn’t —
if errormessage in kwargs:
print("yeah it's here")
I’m guessing because kwargs is iterable? Do I have to iterate through it just to check if a particular key is there?
You want
To get the value of
errormessageIn this way,
kwargsis just anotherdict. 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 aKeyError.Your second example,
if errormessage in kwargs:, means “ifkwargscontains the element named by “errormessage“, and unless “errormessage” is the name of a variable, you’ll get aNameError.I should mention that dictionaries also have a method
.get()which accepts a default parameter (itself defaulting toNone), so thatkwargs.get("errormessage")returns the value if that key exists andNoneotherwise (similarlykwargs.get("errormessage", 17)does what you might think it does). When you don’t care about the difference between the key existing and havingNoneas a value or the key not existing, this can be handy.