Python setdefault not lvalue, any work-arounds?
Question: I have the following small program:

    
    
    ages=[23,23,43,54,34,22,43,23]
    
    histogram={}
    for age in ages:
        if not age in histogram:
            histogram[age]=1
        else:
            histogram[age]+=1
    
    for age,count in sorted(histogram.items()):
        print "Age: %d Number of people: %d"%(age,count)
    

It creates a simple histogram of the ages of people in a list. However, I find
the double lookup in the histogram hash quite unsightly. I know hash access is
basically O(1), so this isn't as inefficient as it may seem, but still...

I've tried various work-arounds, such as trying to use setdefault, but the
following won't fly:

    
    
    histogram.setdefault("age",0)+=1 #<- Incorrect
    

I know I can use defaultdict, but it changes the behaviour of the created
histogram dict object, which is not what I want.

If there were a way for me to set this question to a "low priority" I would,
because obviously this isn't very important. But I've been looking for a
clever and/or elegant solution to this problem for a long time.

So, the question is: How to increment an integer by a key in a dict, or set it
to 1 if it doesn't exist?


Answer: For this particular application, you should use [a
`Counter`](http://docs.python.org/library/collections.html#collections.Counter).

    
    
    from collections import Counter
    
    ages = [23,23,43,54,34,22,43,23]
    
    histogram = Counter(ages)
    
    for age,count in sorted(histogram.items()):
        print "Age: %d Number of people: %d"%(age,count)
    

If you really need a `dict`, you could convert the Counter back to a dict with
the `dict` constructor.

    
    
    histogram = dict(Counter(args))
    

