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. 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. 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?
You are testing if a
the same object as a random empty dictionary, not if that dictionary has the key height
. is not
and is
test for identity , not equality.
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:
return a.get('height', 0)
or use not a
to test for an empty dictionary:
return a['height'] if a else 0
but note you'll still get a KeyError
if the dictionary has keys other than 'height'
. All empty containers test as false in a boolean context, see Truth Value Testing .
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:
return a.get('height', 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.