Il 17/12/2020 13:33, Chris Angelico ha scritto:
On Thu, Dec 17, 2020 at 11:16 PM jak <nos...@please.ty> wrote:
Il 17/12/2020 12:40, Peter J. Holzer ha scritto:
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
this one?
""""
D['a'] if 'a' in D else get_default()
ChrisA
""""
This solution search two times same key.
Yes, it does, but hash lookups are pretty fast. Unless your key is
some sort of custom object with a very expensive __hash__ function,
the double lookup isn't going to be too costly. But if that does
bother you, you can write it as a try/except instead.
ChrisA
try/except is a very expensive time. if we have a small dictionary in
which you do little research, you definitely have reason. I would be
curious to see the differences by taking times with 50 / 60K records by
repeating the search 1 or 2 million times with and without try/except
and also searching 1 or 2 times too.
Cheers
--
https://mail.python.org/mailman/listinfo/python-list