Is there a short-circuiting dictionary "get" method?

Bengt Richter bokr at oz.net
Fri Mar 11 05:03:07 EST 2005


On Fri, 11 Mar 2005 04:12:19 -0500, Steve Holden <steve at holdenweb.com> wrote:

>Terry Reedy wrote:
>> "Skip Montanaro" <skip at pobox.com> wrote in message 
>> news:16943.18475.568383.983546 at montanaro.dyndns.org...
>> 
>>>   value = d.get('x') or bsf()
>>>
>>>Of course, this bsf() will get called if d['x'] evaluates to false, not 
>>>just
>>>None,
>> 
>> 
>> value = (d.get('x') is not None) or bsf() #??
>> 
>Unfortunately this will set value to True for all non-None values of 
>d['x']. Suppose d['x'] == 3:
>
>  >>> 3 is not None
>True
>  >>>
>
maybe (untested)
   value = ('x' in d and [d['x']] or [bsf()])[0]

then there's always

   if 'x' in d: value = d['x']
   else: value = bsf()

or

   try: value = d['x']
   except KeyError: value = bsf()


Regards,
Bengt Richter



More information about the Python-list mailing list