How to check if a key exists in ** kwargs?

Python 3.2.3. There were some ideas listed here that work on regular var, but it seems ** kwargs play by different rules ... so why doesn’t it work and how can I check if the key exists in ** kwargs?

if kwargs['errormessage']: print("It exists") 

I also think this should work, but it is not -

 if errormessage in kwargs: print("yeah it here") 

I guess because kwargs fighter? Do I need to go through it to check if there is any specific key?

+90
python dictionary kwargs
Sep 13 '12 at 5:14
source share
6 answers

Do you want

 if 'errormessage' in kwargs: print("found it") 

To get the errormessage value

 if 'errormessage' in kwargs: print("errormessage equals " + kwargs.get("errormessage")) 

So kwargs is just another dict . Your first example, if kwargs['errormessage'] , means "get the value associated with the" errormessage "key in kwargs, and then check its bool value." So if there is no such key, you will get a KeyError .

Your second example, if errormessage in kwargs: means "if kwargs contains an element named" errormessage ", and if" errormessage "is not a variable name, you will get a NameError .

I should note that the dictionaries also have a .get() method that accepts the default parameter (default is None ), so kwargs.get("errormessage") returns a value if this key exists, and None otherwise (similarly kwargs.get("errormessage", 17) does what you think it does). If you don't care about the difference between an existing key and a None value as a value or a nonexistent key, this can be convenient.

+132
Sep 13 '12 at 5:17
source share

Answers DSM and Tadeck answer your question directly.

In my scripts, I often use the convenient dict.pop() to handle optional and optional arguments. Here is an example of a simple print() wrapper:

 def my_print(*args, **kwargs): prefix = kwargs.pop('prefix', '') print(prefix, *args, **kwargs) 

Then:

 >>> my_print('eggs') eggs >>> my_print('eggs', prefix='spam') spam eggs 

As you can see, if prefix not contained in kwargs , then by default '' (empty string) is stored in the local prefix variable. If it is specified, then its value is used.

This is usually a compact and readable recipe for writing wrappers for any function: always just passed arguments that you don’t understand, and don’t even know if they exist. If you always go through *args and **kwargs , you make your code slower and require a bit more typing, but if the interface of the called function (in this case print ) changes, you do not need to change your code. This approach reduces development time by supporting all interface changes.

+19
Sep 13 '12 at 9:35
source share

It's simple:

 if 'errormessage' in kwargs: print("yeah it here") 

You need to check if the key is in the dictionary. The syntax for this is some_key in some_dict (where some_key is something hashed, not necessarily a string).

The ideas you linked ( these ideas ) contained examples of checking if a particular key existed in the dictionaries returned by locals() and globals() . Your example is similar because you are checking for a specific key in the kwargs dictionary (a dictionary containing keywords).

+10
Sep 13 '12 at 5:19
source share

One way is to add it yourself! How? By merging kwargs with a bunch of defaults. This will not be appropriate in all cases, for example, if the keys are not known to you in advance. However, if they are, here is a simple example:

 import sys def myfunc(**kwargs): args = {'country':'England','town':'London', 'currency':'Pound', 'language':'English'} diff = set(kwargs.keys()) - set(args.keys()) if diff: print("Invalid args:",tuple(diff),file=sys.stderr) return args.update(kwargs) print(args) 

The default values ​​are set in the args dictionaries, which include all the keys we expect. First we check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which overwrite any new values ​​that the user has set. We don’t need to check if the key exists, now we use args as a dictionary of arguments and no longer need kwargs .

+2
Sep 13
source share

You can easily find these things yourself:

 def hello(*args, **kwargs): print kwargs print type(kwargs) print dir(kwargs) hello(what="world") 
+1
Sep 13 '12 at 7:24
source share
 if kwarg.__len__() != 0: print(kwarg) 
0
Aug 16 '19 at 4:45
source share



All Articles