如何检查** kwargs中的密钥是否存在?

时间:2021-01-02 23:46:51

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?

Python 3.2.3。这里列出了一些想法,这些想法适用于常规var,但似乎** kwargs按照不同的规则进行播放...所以为什么这不起作用,我怎样才能检查** kwargs中是否存在关键字?

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?

我猜是因为kwargs是可迭代的?我是否必须迭代它才能检查特定键是否存在?

5 个解决方案

#1


96  

You want

你要

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

To get the value of errormessage

获取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.

通过这种方式,kwargs只是另一个词。你的第一个例子,如果kwargs ['errormessage'],意味着“获取与密钥相关的值”errormessage“在kwargs中,然后检查它的bool值”。因此,如果没有这样的密钥,您将获得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.

你的第二个例子,如果kwargs中的errormessage:,则表示“如果kwargs包含由”errormessage“命名的元素,除非”errormessage“是变量的名称,否则你将得到一个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.

我应该提到字典也有一个方法.get()接受一个默认参数(本身默认为None),这样kwargs.get(“errormessage”)返回值,如果该键存在,否则为None(类似于kwargs.get) (“errormessage”,17)做你可能认为它做的事情)。当您不关心现有密钥与将None作为值或密钥不存在之间的区别时,这可能很方便。

#2


15  

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:

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

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.

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

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.

这通常是一个紧凑且可读的配方,用于为任何类型的函数编写包装器:始终只是您不理解的传递参数,甚至不知道它们是否存在。如果你总是通过* args和** kwargs你使代码变慢,并且需要更多的输入,但是如果被调用函数的接口(在本例中为print)发生了变化,则不需要更改代码。这种方法缩短了开发时间,同时支持所有接口更改

#3


8  

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).

如果密钥在字典中,您需要检查。其语法是some_dict中的some_key(其中some_key是可以删除的东西,不一定是字符串)。

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).

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

#4


2  

One way is to add it 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 know to you in advance. However if they are, here is a simple example:

一种方法是自己添加!怎么样?通过将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)

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.

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

#5


1  

You can discover those things easily by yourself:

您可以自己轻松发现这些事情:

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

hello(what="world")

#1


96  

You want

你要

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

To get the value of errormessage

获取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.

通过这种方式,kwargs只是另一个词。你的第一个例子,如果kwargs ['errormessage'],意味着“获取与密钥相关的值”errormessage“在kwargs中,然后检查它的bool值”。因此,如果没有这样的密钥,您将获得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.

你的第二个例子,如果kwargs中的errormessage:,则表示“如果kwargs包含由”errormessage“命名的元素,除非”errormessage“是变量的名称,否则你将得到一个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.

我应该提到字典也有一个方法.get()接受一个默认参数(本身默认为None),这样kwargs.get(“errormessage”)返回值,如果该键存在,否则为None(类似于kwargs.get) (“errormessage”,17)做你可能认为它做的事情)。当您不关心现有密钥与将None作为值或密钥不存在之间的区别时,这可能很方便。

#2


15  

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:

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

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.

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

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.

这通常是一个紧凑且可读的配方,用于为任何类型的函数编写包装器:始终只是您不理解的传递参数,甚至不知道它们是否存在。如果你总是通过* args和** kwargs你使代码变慢,并且需要更多的输入,但是如果被调用函数的接口(在本例中为print)发生了变化,则不需要更改代码。这种方法缩短了开发时间,同时支持所有接口更改

#3


8  

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).

如果密钥在字典中,您需要检查。其语法是some_dict中的some_key(其中some_key是可以删除的东西,不一定是字符串)。

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).

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

#4


2  

One way is to add it 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 know to you in advance. However if they are, here is a simple example:

一种方法是自己添加!怎么样?通过将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)

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.

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

#5


1  

You can discover those things easily by yourself:

您可以自己轻松发现这些事情:

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

hello(what="world")