Python dictionary get method in assignment
Question: All,

I'm looping over a dictionary and counting the values that occur. To do this,
I'm using the get method in the assignment statement for another dictionary.
This returns a syntax error "can't assign to function call"

    
    
    counts = {}
    mydict = {'a':[1,2,5], 'b': [1,2,10]}
    for key,value in mydict.iteritems():
        counts(value[1]) = counts.get(value[1], 0) + 1
    

Why would the assignment try to point to the function, rather than the return
value?


Answer: 
    counts = {}
    mydict = {'a':[1,2,5], 'b': [1,2,10]}
    for key,value in mydict.iteritems():
        counts[value[1]] = counts.get(value[1], 0) + 1
    

You need brackets, not parenthesis, to get an item from a dictionary.

Also, You're doing this the hard way.

    
    
    from collections import defaultdict
    
    # automatically start each count at zero
    counts = defaultdict(int)
    # we only need the values, not the keys
    for value in mydict.itervalues(): 
        # add one to the count for this item
        counts[value[1]] += 1
    

or

    
    
    # only on Python 2.7 or newer
    from collections import Counter
    
    counts = Counter(value[1] for value in mydict.itervalues())
    

