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

Peter J. Holzer hjp-python at hjp.at
Thu Dec 17 06:40:49 EST 2020


On 2020-12-17 12:16:29 +0100, jak wrote:
> print(_ if d.get('a', None) is not None else get_default())

That doesn't work:

>>> print(_ if d.get('a', None) is not None else get_default())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined

But this works:

>>> print(_ if (_ := d.get('a', None)) is not None else get_default())
1

(I would prefer ChrisA's solution, though.)

        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/20201217/a5ac46be/attachment.sig>


More information about the Python-list mailing list