for key1 in groups:
    combined[key1] = []
key1_ab, key1_string = unpack_key(key1)
for key2 in groups:
    if key1 != key2:
        key2_ab, key2_string = unpack_key(key2)
if key1_ab == key2_ab and len(key1_string) == len(key2_string):
    if hamming(key1_string, key2_string) <= 2:
        combined[key1].append(key2)
Python - grouping defaultdict values by hamming distance in keys