Dictionary KeyError - I know where problem is, but I need help fixing it

All I want if to increment value for a given key. For example, the string that appears representing g key ‘USA’ should have value updated. But I get a KeyError since it appears this is happening because the key cannot be incremented as shown below. Please kindly assist on how I can solve this?

import re

d = {}
def listdict(string):

pattern = "^(USA_239*)/?"
if re.match(pattern, string):
    print("Found a match...")   
    key_id = pattern.strip("^(_239*)/?")
    try:
        #Getting error if I attempt to increment a key...
        d[key_id] =  d[key_id] + 1
    except KeyError:
        
        print("Key doesnt exist")

return d

string = “USA_239_3958_SPFOFI”
print(listdict(string))
string = “USA_239_4058_SPFOI”
print(listdict(string))

You can’t increment the value if it doesn’t exist. Lots of ways to solve this. I like to use counters when the values are numeric.

from collections import Counter
d = Counter()
...
d[key_id] += 1

You can also use defaultdict (not shown)
There’s also the option of setdefault.

d = {}
...
d[key_id] = d.setdefault(key_id, 0) + 1

I’d prefer those over the more manual:

d = {}
...
if key_id not in d:
    d[key_id] = 0
d[key_id] += 1
2 Likes

There’s another way that you omitted:

d[key_id] = d.get(key_id, 0) + 1

Yes, indeed. Not sure why that was one I missed. It’s simpler and clearer than many alternatives.