Python3 – Intersecting dictionaries and merging their values into a list

Question:

Given the two dictionaries:

dict1 = { 1:'A', 2:'B', 3:'C' }
dict2 = { 1:'X', 2:'Y' }

I need to intersect those dictionaries by keys (remove those entries which keys aren’t available in both dictionaries) AND combine them into one dictionary with the list as values:

result = { 1:['A','X'], 2:['B','Y'] }

So far I’ve only merge those two dictionaries into one, but without removing mentioned entries with:

{key:[dict1[key], dict2[key]] for key in dict1}
Asked By: nikodamn

||

Answers:

for each key of dict1 check if the key exist in dict2 and do your merge after it

dict1 = { 1:'A', 2:'B', 3:'C' }
dict2 = { 1:'X', 2:'Y' }

result = {}

for key in dict1:
    if key in dict2:
        result[key] = [dict1[key], dict2[key]]

Answered By: Antoine Koiko

You can just check if it exists in the keys of the other and append it. This would deal with any number of strings as values.

x = { 1:'A', 2:'B', 3:'C' }
y = { 1:'X', 2:'Y' }

for k, v in x.items():
    if k in y.keys():
        y[k] = [y[k]]
        y[k].append(v)
    else:
        y[k] = [v]
    
print(y)
Answered By: anisoleanime
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.