I have two arrays
A = [a, b, c, d]
and
B = [a1, a2, b1, b2, b3, c1, c2, c3, d1, d2, d3, d4]
I want to match b
from collections import defaultdict A = ["a", "b", "c", "d"] B = ["a1", "a2", "b1", "b2", "b3", "c1", "c2", "c3", "d1", "d2", "d3", "d4"] d = defaultdict(list) for item in B: prefix = item[0] if prefix in A: d[prefix].append(item)