-3

Input: [('Vehicle=Boat', 'Tom'), ('Vehicle=Car', 'Scott'), ('Vehicle=Car', 'Tom'), ('Vehicle=Boat', 'Tom')]

Using the following code I can group the input properly but counting the occurrences within the tuple is giving me problems:

def groupBy(seqs, idx=1): 
    
    d = dict()
    for seq in seqs:
        k = seq[idx]
        v = d.get(k,tuple()) + (seq[:idx]+seq[idx+1:]) #new dict here where mydict[i] = count.get(i,0) + 1?
        d.update({k:v})
    return d

Returns:

{'Tom': ('Vehicle=Boat', 'Vehicle=Car', 'Vehicle=Boat'), 'Scott': ('Vehicle=Car')}

This is great, but I would like the output to be:

Tom  
Vehicle=Boat: 2  
Vehicle=Car: 1  

Scott 
Vehicle=Car: 1

Could someone please point me in the right direction?

Leroy Jenkins
  • 2,680
  • 6
  • 25
  • 33

1 Answers1

1

You just crunch it by hand:

data = [('Vehicle=Boat', 'Tom'), ('Vehicle=Car', 'Scott'), ('Vehicle=Car', 'Tom'), ('Vehicle=Boat', 'Tom')]

def groupBy(seqs, idx=0): 
    d = {}
    for seq in seqs:
        k = seq[idx]
        if k not in d:
            d[k] = {}
        rest = seq[:idx] + seq[idx+1:]
        if rest not in d[k]:
            d[k][rest] = 0
        d[k][rest] += 1
    return d

print( groupBy( data, 1 ) )

Output:

{'Tom': {('Vehicle=Boat',): 2, ('Vehicle=Car',): 1}, 'Scott': {('Vehicle=Car',): 1}}
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30