[英]Checking if dictionary is empty using conditional statement in python is throwing a key error
I am sort of new to Python so I was reading through Pro Python and it had this section about passing variable keyword arguments to function. 我是Python的新手,所以我通读了Pro Python,其中包含有关将变量关键字参数传递给函数的部分。 After reading that section I wrote the following code which doesn't seem to work.
阅读该部分后,我写了以下似乎无效的代码。
def fun(**a):
return a['height'] if a is not {} else 0
I got a key error when I called fun with no arguments. 当我不带参数调用fun时遇到了一个关键错误。 How should I change the code so that it returns a['height'] if a is not a null dictionary and returns 0 if it is a null dictionary?
我应该如何更改代码,以便如果a不是空字典,则返回a ['height'],如果是空字典,则返回0?
You are testing if a
the same object as a random empty dictionary, not if that dictionary has the key height
. 您正在测试
a
是与随机空字典相同的对象 ,而不是该字典是否具有key height
。 is not
and is
test for identity , not equality. is not
, is
测试身份 ,而不是平等。
You can create any number of empty dictionaries, but they would not be the same object : 您可以创建任意数量的空字典,但它们不是同一对象 :
>>> a = {}
>>> b = {}
>>> a == b
True
>>> a is b
False
If you want to return a default value if a key is missing, use the dict.get()
method here: 如果要在缺少键的情况下返回默认值,请在此处使用
dict.get()
方法 :
return a.get('height', 0)
or use not a
to test for an empty dictionary: 或
not a
使用not a
来测试空字典:
return a['height'] if a else 0
but note you'll still get a KeyError
if the dictionary has keys other than 'height'
. 但是请注意,如果字典中除了
'height'
以外'height'
键,您仍然会收到KeyError
。 All empty containers test as false in a boolean context, see Truth Value Testing . 在布尔上下文中,所有空容器都将测试为false ,请参阅“ 真值测试” 。
To check if a dictionary has a specific key, do this: 要检查字典是否具有特定的键,请执行以下操作:
if 'height' not in a: return 0
Or you can use get()
with a default: 或者您可以使用默认的
get()
:
return a.get('height', 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.