A few ways:
dict.get
for k in li:
d[k] = d.get(k,0) + 2
setdefault
for k in li:
d[k] = d.setdefault(k,0) + 2
You'll notice that this is basically equivalent to the get
syntax. The difference between the two is that the call to setdefault
actually creates the default value if it doesn't yet exist, so you could alternatively write:
for k in li:
d.setdefault(k,0)
d[k] += 2
use a defaultdict
from collections import defaultdict
d = defaultdict(int)
for k in list:
d[k] += 2
(don't name your lists list
, don't name your dicts dict
; those names shadow the built-in types)