Python dictionary: add or increment entry
Posted
by cursa
on Stack Overflow
See other posts from Stack Overflow
or by cursa
Published on 2010-04-12T23:13:12Z
Indexed on
2010/04/12
23:32 UTC
Read the original article
Hit count: 641
Hi everyone,
I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way.
The code that I'm writing is in the following form:
# foo is a dictionary
if foo.has_key(bar):
foo[bar] += 1
else:
foo[bar] = 1
I'm writing this a lot in my programs. My first reaction is to push it out to a helper function, but so often the python libraries supply things like this already.
Is there some simple little syntax trick that I'm missing? Or is this the way that it should be done?
© Stack Overflow or respective owner