Checking if dictionary is empty using conditional statement in python is throwing a key error -
i sort of new python reading through pro python , had section passing variable keyword arguments function. after reading section wrote following code doesn't seem work.
def fun(**a): return a['height'] if not {} else 0 i got key error when called fun no arguments. how should change code returns a['height'] if not null dictionary , returns 0 if null dictionary?
you testing if a the same object random empty dictionary, not if dictionary has key height. is not , is test identity, not equality.
you can create number of empty dictionaries, not same object:
>>> = {} >>> b = {} >>> == b true >>> b false if want return default value if key missing, use dict.get() method here:
return a.get('height', 0) or use not a test empty dictionary:
return a['height'] if else 0 but note you'll still keyerror if dictionary has keys other 'height'. empty containers test false in boolean context, see truth value testing.
Comments
Post a Comment