I am having this piece of code, which in my opinion is fairly ugly and I am wondering how it can be done better:
if dic.get(key, None) is None:
dic[key] = None
Points for elegance ;-)
I am having this piece of code, which in my opinion is fairly ugly and I am wondering how it can be done better:
if dic.get(key, None) is None:
dic[key] = None
Points for elegance ;-)
if key not in dic:
dic[key] = None
This might not be as short as Olivier's code, but at least it's explicit and fast.
Please, don't use dict
as a variable name, it shadows built-in.
import collections
mydict = collections.defaultdict(lambda: None)
Now, any access to mydict[akey]
will (if akey
was not present as a key in mydict
) set mydict[akey]
to None
as a side effect.
Note that defaultdict
's initializer requires a no-arguments callable, whence the lambda
.