Steven G
Steven G

Reputation: 17122

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!

Upvotes: 0

Views: 3253

Answers (6)

saturdayplace
saturdayplace

Reputation: 8720

Sounds like what you really want is a Counter:

https://docs.python.org/2/library/collections.html#collections.Counter https://docs.python.org/3.6/library/collections.html#collections.Counter

from collections import Counter
c = Counter()

for key in ['a', 'b', 'c']:
    for i in range(10):
        c[key] += i

Upvotes: 1

Robert Valencia
Robert Valencia

Reputation: 1752

You can filter for the keys that exist within the dictionary by using list comprehension and a conditional, then iterate through that, like so:

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

for key in [key for key in ['a', 'b', 'c'] if key in x.keys()]:
    for i in range(0, 10):
        x[key] += i

print x

Outputs

{'a': 45, 'b': 45}

Upvotes: 0

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

try this

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

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

Upvotes: 2

DSLima90
DSLima90

Reputation: 2838

maybe you can use the method get of dictionaries

try this:

x[key] = x.get(key,0) +i

the full code:

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

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

Upvotes: 2

valeas
valeas

Reputation: 384

You can check right before adding i if the element is in the dictionary. If it isn't, you create a new element and put the default value 0. Then you act normal and add i

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

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

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599580

Use a defaultdict

from collections import defaultdict
x = defaultdict(int)

Upvotes: 8

Related Questions