开发者

small python code refactor

I am having this piece of code, which in my opinion is fairly ugly and I am wondering how 开发者_Python百科it can be done better:

if dic.get(key, None) is None:
   dic[key] = None

Points for elegance ;-)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜