dict.get(key, default) evaluates default even if key exists

Peter J. Holzer hjp-python at hjp.at
Wed Dec 16 06:08:23 EST 2020


On 2020-12-15 13:07:25 -0800, Ethan Furman wrote:
> On 12/15/20 9:07 AM, Mark Polesky via Python-list wrote:
> 
> > D = {'a':1}
> >
> > def get_default():
> >      print('Nobody expects this')
> >      return 0
> >
> > print(D.get('a', get_default()))
> 
> Python has short-circuiting logical operations, so one way to get the behavior you're looking for is:
> 
>     D.get('a') or get_default()

That will call get_default for any falsey value (0, "", an empty list ...),
not just for missing values.

Which may or may not be what the OP wants.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20201216/28ee3425/attachment.sig>


More information about the Python-list mailing list