Reputation: 129
I have question a bit similar to:Replacing the value of a Python dictionary with the value of another dictionary that matches the other dictionaries key
However in my case I got two dictionaries
dict1 = {'foo' : ['val1' , 'val2' , 'val3'] , 'bar' : ['val4' , 'val5']}
dict2 = {'foo' : ['val2', 'val10', 'val11'] , 'bar' : ['val1' , 'val4']}
What I want to return is
dict3 = {'foo' : ['val10', 'val11'] , 'bar' : ['val1']}
and the opposite which is
dict4 = {'foo' : ['val1', 'val3'] , 'bar' : ['val5']}
where dict3 returns a dictionary of the values the keys 'foo' and 'bar' has gained in dict2 and the dict4 is a dictionary of the values the keys 'foo' and 'bar' has lost in dict2
One way I have tried solving this is to:
iterate over both dictionaries then
if key of dict1 == key of dict2
return the values of the key in dict1 and compare with the values in dict2
return the values that aren't in both
as a dictionary of the key and those values
This idea isn't working and obviously highly inefficient. I was hoping there is a more efficient working way to do this
Upvotes: 2
Views: 53
Reputation: 26315
Two dict comprehensions will do the trick:
dict3 = {k: [x for x in v if x not in dict1[k]] for k, v in dict2.items()}
print(dict3)
# {'foo': ['val10', 'val11'], 'bar': ['val1']}
dict4 = {k: [x for x in v if x not in dict2[k]] for k, v in dict1.items()}
print(dict4)
# {'foo': ['val1', 'val3'], 'bar': ['val5']}
The above two comprehensions basically filter out the values from key that don't exist in the other dictionary, which is done both ways.
You can also do this without dict comprehensions:
dict3 = {}
for k,v in dict2.items():
dict3[k] = [x for x in v if x not in dict1[k]]
print(dict3)
# {'foo': ['val10', 'val11'], 'bar': ['val1']}
dict4 = {}
for k,v in dict1.items():
dict4[k] = [x for x in v if x not in dict2[k]]
print(dict4)
# {'foo': ['val1', 'val3'], 'bar': ['val5']}
Upvotes: 3