Find intersection of dictionary values list

Viewed 66

I have two dictionaries with the same keys, while the values are variant:

a = {1: [1, 2, 3, 4, 5], 2: [6, 7, 8], 3: [1, 3, 5, 7, 9]}
b = {1: [2, 3, 4, 7], 2: [6, 7], 3: [1, 3, 15, 10]}

I'm trying to get the intersection under the same keys. I want this output:

{1: [2, 3, 4], 2: [6, 7], 3: [1, 3]}

I tried with this command:

dict(zip(a.keys() and b.keys(), a.values() and b.values()))
output: {1: [2, 3, 4, 7], 2: [6, 7], 3: [1, 3, 15, 10]}

However, the output is the following, which is wrong:

{1: [2, 3, 4, 7], 2: [6, 7], 3: [1, 3, 15, 10]}
3 Answers

I think it is pretty clear. If not, please ask for clarification.

Assuming,

I have two dictionaries with the same keys

a = {1: [1, 2, 3, 4, 5], 2: [6, 7, 8], 3: [1, 3, 5, 7, 9]}
b = {1: [2, 3, 4, 7], 2: [6, 7], 3: [1, 3, 15, 10]}
c = {}

for key, val in a.items():
    c[key] = []
    for i in val:
        if i in b[key]:
            c[key].append(i)

print(c)

The output is:

{1: [2, 3, 4], 2: [6, 7], 3: [1, 3]}

If you know the dictionaries have the same keys, you could do

c = {}
for key, list_a, list_b in zip(a.keys(), a.values(), b.values()):
    c[key] = [value for value in list_a if value in list_b]

Or:

c = {}
for key, list_a, list_b in zip(a.keys(), a.values(), b.values()):
    c[key] = list(set(list_a).intersection(list_b))

If you're not sure they have the same keys, just add a condition, like

c = {}
for key_a, list_a, key_b, list_b in zip(a.keys(), a.values(), b.keys(), b.values()):
    if key_a == key_b:
        c[key_a] = [value for value in list_a if value in list_b]
c= {key:list(set(a[key]) & set(b[key])) for key in a}

Explanation: using dictionary comprehension, I went through each key of 'a', & create an intersection of list of values corresponding to that key in both the dictionaries 'a' & 'b'

Related