0

I want a dictionary that shows boolean counts. I.e. how often name/position combination meets criteria. E.g.:

Key - Value1 - Value2
John12 Yes:300 No:25 
John13 Yes:400 No:29 
Linda13 Yes:300 No:60 

...

I tried this:

if str(f[1]) + str(f[7]) in psHpGrp:
    if f[6] == 1:
        psHpGrp.setdefault(str(f[1]) + str(f[7]), []) +=1

And because of a bug I got "SyntaxError: illegal expression for augmented assignment"

So googling gave me this:

if str(f[1]) + str(f[7]) in psHpGrp:
    if f[6] == 1:
        i = psHpGrp.setdefault((f[1]) + str(f[7]), [])
        i += 1    
    else:
        j = psHpGrp.setdefault((f[1]) + str(f[7]), [])
        j += 1 
else:
    psHpGrp.setdefault(str(f[1]) + str(f[7]), []).append(str(f[1]) + str(f[7]))    

And now I get: j += 1 'int' object is not iterable

Whats wrong here?

Alfe
  • 56,346
  • 20
  • 107
  • 159
AWE
  • 4,045
  • 9
  • 33
  • 42

3 Answers3

4

You want to use defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['a'] += 1
>>> d['b'] += 1
>>> d['b'] += 1
>>> print d['a'], d['b'], d['c']
1 2 0
Ricardo Cárdenes
  • 9,004
  • 1
  • 21
  • 34
  • 1
    Just to make it clear: `defaultdict` is instantiated with a certain class (in this case, `int`). If you retrieve a key that is not in the dictionary, it's first initialized to `defaultclass()` and then returned (ie. there's never a `KeyError` for this dict). `int()` is `0`, as you may test :) – Ricardo Cárdenes May 23 '12 at 11:41
0
from collections import Counter

psHpGrp.setdefault(str(f[1]) + str(f[7]), Counter()).update([f[6] == 1])

The first part:

psHpGrp.setdefault(str(f[1]) + str(f[7]), Counter())

will take the object for the key str(f[1]) + str(f[7]) from the dictionary psHpGrp and if it is not present, create a new Counter.

Then it will .update([f[6] == 1]) it with the result of the condition f[6] == 1, which can be True or False. The Counter holds then the number of Trues and Falses as a dictionary. They represent your "Yes"/"No", just they are booleans.

eumiro
  • 207,213
  • 34
  • 299
  • 261
0

like @larsmans said, you can't add an int to a list (using +=). On your initial attempt replace [] with 0, and then increment the number for that entry.

if str(f[1]) + str(f[7]) in psHpGrp:
    if f[6] == 1:
        psHpKey = str(f[1]) + str(f[7])
        psHpGrp.setdefault(psHpKey, 0)
        psHpGrp.setdefault[psHpKey] +=1

Also: Your final error seems to be arising from code that you have not posted. Python lets you know on which line the offending code is, it's best to post at least that line of code.

vikki
  • 2,766
  • 1
  • 20
  • 26