2

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

Mykel
  • 119
  • 1
  • 9

1 Answers1

3

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']}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • Thanks. That was clear and worked. Is there a place I can learn more dict comprehensions? – Mykel Nov 15 '18 at 02:36
  • 1
    @Mykel You can try following [www.datacamp.com/community/tutorials/python-dictionary-comprehension](https://www.datacamp.com/community/tutorials/python-dictionary-comprehension). This is a good tutorial on dictionaries in general, including dict comprehensions. Also note that you don't have to use dict comprehensions, they are just handy for making quick one liners. The above can be easily done without them, it just requires more code. – RoadRunner Nov 15 '18 at 02:38
  • 1
    I understand that other method requires more code. Dict comprehensions however are very handy and I am hoping to understand more of them. Thanks again – Mykel Nov 15 '18 at 02:47
  • 1
    @Mykel Yeah, they are very handy. If you understand list comprehensions, they are the same idea, just slightly different syntax. No problem man :). – RoadRunner Nov 15 '18 at 02:48