Search code examples
pythondictionarytry-catchkeyerror

pythonic way to add value to a dict key but if doesn't exist start it to 0 and then add the value


I am trying to simplify an operation over a dictionary. problem is, sometimes the key doesn't exist, so I have to first try for KeyError but I feel like I am overdoing it.

example:

x = {'a': 0, 'b': 0}

for key in ['a', 'b', 'c']:
    for i in range(0, 10):
        try:
            x[key] += i
        except KeyError:
            x[key] = 0
            x[key] += i

as you can see here, the 'c' key doesnt exist, so I try first. I am looking for a way to skip the try part if that is possible.

Thanks!


Solution

  • Use a defaultdict

    from collections import defaultdict
    x = defaultdict(int)