Reputation: 79
I have two dictionaries that I want to match by key in order to create a new dictionary with every value in dict1 as key and an list of each matching key's values in dict2 as the value in the output. The example should be less confusing:
dict1 = {'AAA': 'id5', 'BBB': 'id3', 'CCC': 'id8', 'DDD': 'id3'}
dict2 = {'AAA': 'value8', 'BBB': 'value24', 'CCC': 'value13', 'DDD': 'value2'}
What I have tried:
keys = set(dict1) & set(dict2)
complete = {}
for x in keys:
key = dict1[x]
value = dict2[x]
complete[key] = [value]
Output:
complete = {'id3': ['value24'], 'id5': ['value8'], 'id8': ['value13']}
Desired output:
complete = {'id3': ['value24', 'value2'], 'id5': ['value8'], 'id8': ['value13']}
In reality the dictionaries are quite large so performance is an important factor. Any help is appreciated.
Upvotes: 0
Views: 143
Reputation: 1121524
The dict.keys()
method returns a dictionary view that already acts as a set. All you need to do is take the union of those views.
If your values from dict1
are not unique, use dict.setdefault()
to build lists of values:
output = {}
for key in dict1.keys() & dict2.keys():
output.setdefault(dict1[key], []).append(dict2[key])
Demo:
>>> dict1 = {'AAA': 'id5', 'BBB': 'id3', 'CCC': 'id8', 'DDD': 'id3'}
>>> dict2 = {'AAA': 'value8', 'BBB': 'value24', 'CCC': 'value13', 'DDD': 'value2'}
>>> output = {}
>>> for key in dict1.keys() & dict2.keys():
... output.setdefault(dict1[key], []).append(dict2[key])
...
>>> output
{'id8': ['value13'], 'id3': ['value24', 'value2'], 'id5': ['value8']}
This is about as efficient as it'll get.
Upvotes: 2