Q:

counting incidences of a number and associated value in two synchronized lists

I have two lists that are of the same length:
alist = ['XX', 'HH', 'GG', 'XX', 'II', 'PP', 'LL', 'TT', 'KK', 'XX']
blist = [2, 3, 5, 5, 9, 8, 9, 4, 7, 2]

I want to know what values in alist have the same number in blist. I want the outcome to look like this:
2 = XX; 3 = HH; 5 = GG, XX; 9 = II, LL; 8 = PP; 4 = TT; 7 = KK
I solved it like this:
from collections import defaultdict
adict = {}
a = zip(blist, alist)
for key, value in a:
    adict.setdefault(k, []).append(v)

which gives this result:
adict:
{2: ['XX', 'XX'], 3: ['HH'], 4: ['TT'], 5: ['GG', 'XX'], 7: ['KK'], 8: ['PP'], 9: ['II', 'LL']}

but I dont want the same value twice, for example 2: ['XX', 'XX'] - I would like to have instead 2: ['XX'].
I tried this using 'set' before the list of values:
a = zip(blist, alist)
for key, value in a:
    a.setdefault(k, set[]).append(v)

but it complained...
any ideas?

A:

I'd personally use Martijn's defaultdict approach, but I thought I'd address the issues with your current attempt.
The problem with your code:
a = zip(blist, alist)
for key, value in a:
    a.setdefault(k, set[]).append(v)

Is That:

after the zip, a is now a list, so it won't support .setdefault
k is not used in the for loop - it should be key
v is not used in the for loop = it should be value
set[] is invalid synatx - to create a new set - use set()
A set does not have an .append - instead you want to use add

Corrected code:
d = {}
a = zip(blist, alist)
for key, value in a:
    d.setdefault(key, set()).add(value)

Adapt the following as desired to print:
for k, v in d.iteritems():
    if k > 5:
        print '{0}: {1}'.format(k, ','.join(v))

