本文介绍了如何检查** kwargs中的键是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.2.3。抱歉,如果这是一个愚蠢的问题,我似乎无法弄清楚或找到答案。有一些想法,它们适用于常规的var,但是似乎** kwargs由不同的规则玩...所以为什么这不工作,我如何检查看看** kwargs中的一个键是否存在?

 如果kwargs ['errormessage']:
print(它存在)

我也认为这应该是有效的,但是它不是 -

 如果在kwargs中的errormessage: 
打印(是啊在这里)

我猜,因为kwargs是可迭代的?

解决方案

你想要

 如果kwargs中的errormessage:
print(found it)

这样, kwargs 只是另一个 dict 。你的第一个例子是如果kwargs ['errormessage'] 表示获取与kwargs中的errormessage键相关的值,然后检查其bool值。所以如果没有这样的密钥,你会得到一个 KeyError



你的第二个例子如果kwargs中的errormessage:,表示if kwargs 包含由 errormessage ,除非 errormessage 是变量的名称,您将得到一个 NameError 。 / p>

我应该提到,字典还有一个方法 .get()它接受一个默认参数(本身默认为),所以 kwargs.get(errormessage)返回值,如果该键存在,否则(同样 kwargs.get(errormessage,17)做你可能会认为的)当你不关心存在的密钥与之间的差异作为值或密钥不存在,这可以方便。


Python 3.2.3. Sorry if this is a dumb question, I can't seem to figure it out or find an answer for it. 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

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

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.

这篇关于如何检查** kwargs中的键是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 17:47