find the difference of two maps in python

To find the difference between two Python dictionaries, we can convert them into sets and perform set operations on them. Here is the code snippet to find the difference of two maps in Python:

main.py
map1 = {'x': 1, 'y': 2, 'z': 3}
map2 = {'x': 1, 'y': 2, 'w': 4}

keys_only_in_map1 = set(map1.keys()) - set(map2.keys())
keys_only_in_map2 = set(map2.keys()) - set(map1.keys())

map_diff = {k: map2[k] for k in keys_only_in_map2}
map_diff.update({k: map1[k] for k in keys_only_in_map1})

print(map_diff)  # prints {'z': 3, 'w': 4}
330 chars
11 lines

Here, we first find the keys that are present only in map1 and only in map2, and then create a new dictionary with the values for these keys. The resulting dictionary map_diff contains the keys that are present only in map1 or only in map2, along with their respective values.

gistlibby LogSnag