4

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?

Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73

4 Answers4

2
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())
agf
  • 171,228
  • 44
  • 289
  • 238
  • Python needs blocks to be indented. Your `for` body is not indented. – cdhowie Aug 18 '11 at 20:20
  • Python needs indentation? I never would have known!! It was just a typo, obviously. – agf Aug 18 '11 at 20:24
  • I'm an idiot, I have got to stop switching languages in the middle of the work day. Also, thanks for pointing out the defaultdict bit, I wasn't aware of that. – Spencer Rathbun Aug 18 '11 at 20:40
1

Instead of counts(value[1]) = ... you want counts[value[1]] = ....

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

Change this:

counts(value[1])

to this:

counts[value[1]]

Code looks like this:

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
hughdbrown
  • 47,733
  • 20
  • 85
  • 108
0
counts[value[1]] = counts.get(value[1], 0) + 1

should be

counts[value[1]] = counts.get(value[1], 0) + 1
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151