This is the purpose of setdefault:
>>> x = {} >>> print x.setdefault.__doc__ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D >>> x.setdefault('a', 5) 5 >>> x {'a': 5} >>> x.setdefault('a', 10) 5 >>> x {'a': 5}
It also means that you can skip the "if" key in dict: ... else: ... "
>>> for val in range(10): ... x.setdefault('total', 0) ... x['total']+=val ... 0 0 1 3 6 10 15 21 28 36 >>> x {'a': 5, 'total': 45}
user2197172
source share