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}
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]]
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)
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}
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]]
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)