I often use python dictionaries as counters. However since dict values are not initialized, I tend to write it like this:
Is there a more elegant way to do this?
(I'm mainly talking about Python2.7, but I also care about python3.x branch)
EDIT:
It works with exceptions like this:
if check(condition):
if dict.has_key(condition):
dict[condition] += 1
else:
dict = 1
The code works and can be singled out in a function that I call in my script, but it feels weird (and very non-pythonic) to rewrite this every time.Is there a more elegant way to do this?
(I'm mainly talking about Python2.7, but I also care about python3.x branch)
EDIT:
It works with exceptions like this:
try:
dict[a] += 1
except KeyError as e:
dict[a] = 1
I hate this. I want pretty code. Got anything better?