问题:如何检查** kwargs键是否存在?

Python 3.2.3。这里列出了一些想法,这些想法可以在常规var上使用,但是** kwargs似乎遵循不同的规则…所以,为什么这行不通?我如何检查** kwargs中的键是否存在?

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

我也认为这应该可行,但是不-

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

我猜是因为kwargs是可迭代的?我是否必须遍历它只是为了检查是否存在特定的密钥?

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?


回答 0

你要

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

获得价值 errormessage

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

这样,kwargs只是另一个dict。您的第一个示例,if kwargs['errormessage']意思是“获取与kwargs中的键“ errormessage”关联的值,然后检查其bool值”。因此,如果没有这样的密钥,您将得到一个KeyError

您的第二个示例if errormessage in kwargs:表示“如果kwargs包含以”命名的元素errormessage,并且除非“ errormessage”是变量的名称,否则您将获得NameError

我应该提到的是,字典也有一个.get()接受默认参数的方法(本身默认为None),以便kwargs.get("errormessage")在该键存在时返回值,None否则返回值(类似地kwargs.get("errormessage", 17),您可能会认为这样做)。当您不关心键的存在与拥有None值或键不存在之间的区别时,这会很方便。

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.


回答 1

DSM和Tadeck的答案将直接回答您的问题。

在我的脚本中,我经常使用便捷dict.pop()来处理可选参数和其他参数。这是一个简单print()包装器的示例:

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

然后:

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

如您所见,如果prefix中未包含kwargs,则默认值''(空字符串)存储在本地prefix变量中。如果给出,则使用其值。

对于编写任何类型的函数的包装程序,通常这是一个紧凑且易读的方法:始终只是传递您不了解的传递参数,甚至不知道它们是否存在。如果您总是通过,*args并且**kwargs使代码变慢,并且需要更多键入,但是如果被调用函数的接口(在这种情况下print)发生了变化,则无需更改代码。这种方法减少了开发时间,同时支持所有接口更改。

DSM’s and Tadeck’s answers answer your question directly.

In my scripts I often use the convenient dict.pop() to deal with optional, and additional arguments. Here’s 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 is not contained in kwargs, then the default '' (empty string) is being stored in the local prefix variable. If it is given, then its value is being used.

This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don’t understand, and don’t even know if they exist. If you always pass through *args and **kwargs you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print) changes, you don’t need to change your code. This approach reduces development time while supporting all interface changes.


回答 2

就是这样:

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

您需要检查密钥是否在字典中。这样做的语法是some_key in some_dict(这里some_key是可哈希的,不一定是字符串)。

您链接的想法(这些想法)包含用于检查locals()and所返回的字典中是否存在特定键的示例globals()。您的示例与此类似,因为您正在检查kwargs字典(包含关键字参数的字典)中是否存在特定键。

It is just this:

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

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

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


回答 3

一种方法是自己添加!怎么样?通过合并kwargs一堆默认值。例如,如果您事先不知道密钥,则此方法不适用于所有情况。但是,如果有,这是一个简单的示例:

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)

默认值在字典中设置,该字典args包括我们期望的所有键。我们首先检查kwarg中是否有任何意外的键。然后我们更新argskwargs,这将覆盖任何新的价值用户已设置。我们不需要测试键是否存在,我们现在将其args用作参数字典,并且不再需要kwargs

One way is to add it by yourself! How? By merging kwargs with a bunch of defaults. This won’t be appropriate on all occasions, 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 defaults are set in the dictionary args, which includes all the keys we are expecting. We first check to see if there are any unexpected keys in kwargs. Then we update args with kwargs which will overwrite any new values that the user has set. We don’t need to test if a key exists, we now use args as our argument dictionary and have no further need of kwargs.


回答 4

您可以自己轻松发现这些东西:

def hello(*args, **kwargs):
    print kwargs
    print type(kwargs)
    print dir(kwargs)

hello(what="world")

You can discover those things easily by yourself:

def hello(*args, **kwargs):
    print kwargs
    print type(kwargs)
    print dir(kwargs)

hello(what="world")

回答 5

if kwarg.__len__() != 0:
    print(kwarg)
if kwarg.__len__() != 0:
    print(kwarg)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。