小python代码重构

hyp*_*ean 0 python dictionary

我有这段代码,在我看来相当丑陋,我想知道如何做得更好:

if dic.get(key, None) is None:
   dic[key] = None
Run Code Online (Sandbox Code Playgroud)

优雅的要点;-)

Oli*_*ier 10

d.setdefault(key) # sets d[key] to None if key is not in d
Run Code Online (Sandbox Code Playgroud)


Sil*_*ost 7

if key not in dic:
    dic[key] = None
Run Code Online (Sandbox Code Playgroud)

这可能不像Olivier的代码那么短,但至少它是明确而快速的.

请不要使用dict变量名称,它内置阴影.