• Coding
  • [Python] Increment or add dictionary value

I often use python dictionaries as counters. However since dict values are not initialized, I tend to write it 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?
I used to have the same problem pre-Groovy 1.8

But ever since, they added a withDefaults
def words = "one two two three three three".split()
def freq = [:].withDefault { k -> 0 }
words.each {
        freq[it] += 1
}
I'll try to find a nicer way in python.
This maybe?
from collections import defaultdict

d = defaultdict(int)
d[100] +=1
Thanks for pointing out the collection module, I did not think about it!

There's a particular one I liked, Counter. It's basically a dict that returns 0 instead of a KeyError exception if the key does not exist.
from collections import Counter

d = Counter()
d[100] += 1
NB: It's only available in (relatively) recent versions (> 2.7)
What are the benefits of a counter? seems to me like its a defaultdict(int) with probably some added functionality.
xterm, you're lazy. I gave the link to the documentation.

Although, here's my favorite Counter method:
most_common([n])

Return a list of the n most common elements and their counts from the most common to the least. If n is not specified, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:
>>>

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Oh! I honestly missed the link.