How do I pythonically set a value in a dictionary if it is None?
You can use dict.setdefault
:
count.setdefault('a', 0)
help on dict.setdefault
:
>>> print dict.setdefault.__doc__
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
setdefault
is the best answer, but for the record, the Pythonic way to check for a key in a dict
is using the in
keyword:
if 'a' not in count:
count['a'] = 0