views:

133

answers:

3

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 ;-)

+7  A: 
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.

SilentGhost
+10  A: 
d.setdefault(key) # sets d[key] to None if key is not in d
Olivier
you don't need to have `None` there explicitly, `default` argument defaults to `None`
SilentGhost
@SilentGhost: hehe, I realised that and changed my answer precisely at the same time as you were writing the comment. :-)
Olivier
This is *considerably* faster than any other method, as it implements the check in C and thus avoids all the temporary reference counting.
Nick Bastin
+3  A: 
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.

Alex Martelli