find the intersection of two maps in python

One way to find the intersection of two maps (dictionaries) in Python is to first convert the keys of each dictionary to sets, and then use the set intersection operator (&) to get a set of the common keys. Finally, you can create a new dictionary by iterating through the common keys and adding the corresponding key-value pairs from both input dictionaries.

Here's an example implementation:

main.py
def dict_intersection(dict1, dict2):
    # create sets of the keys of each dictionary
    keys1 = set(dict1.keys())
    keys2 = set(dict2.keys())

    # compute the intersection of the two sets of keys
    common_keys = keys1 & keys2

    # create a new dictionary with key-value pairs from both dictionaries for common keys
    intersection = {}
    for key in common_keys:
        value1 = dict1[key]
        value2 = dict2[key]
        intersection[key] = (value1, value2)

    return intersection
501 chars
17 lines

Here's an example usage:

main.py
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'b': 4, 'c': 3, 'd': 5}
>>> dict_intersection(dict1, dict2)
{'b': (2, 4), 'c': (3, 3)}
137 chars
5 lines

In this example, the keys 'b' and 'c' are common to both input dictionaries, so the output dictionary contains these keys along with their corresponding values from both input dictionaries.

gistlibby LogSnag