0

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?

1
  • I love it! Three identical answers within one minute! Commented Apr 24, 2015 at 21:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Yours takes a different approach than the rest.. But you seem to have not finished the code sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.