hyperboreean
hyperboreean

Reputation: 8333

small python code refactor

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

Upvotes: 0

Views: 193

Answers (3)

SilentGhost
SilentGhost

Reputation: 319601

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.

Upvotes: 7

Alex Martelli
Alex Martelli

Reputation: 881665

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.

Upvotes: 3

Olivier Verdier
Olivier Verdier

Reputation: 49146

d.setdefault(key) # sets d[key] to None if key is not in d

Upvotes: 10

Related Questions