Fix Python – How To Check If A Key in **kwargs Exists?


Asked By – Zamphatta

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?

Now we will see solution for issue: How To Check If A Key in **kwargs Exists?


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.

This question is answered By – DSM

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0