find the union of two maps in python

To find the union of two maps (or dictionaries) in Python, you can use the built-in update() method to merge the keys and values of one map into the other. Here's an example:

main.py
map1 = {"a": 1, "b": 2, "c": 3}
map2 = {"b": 4, "d": 5, "e": 6}

map1.update(map2)

print(map1)  # Output: {'a': 1, 'b': 4, 'c': 3, 'd': 5, 'e': 6}
148 chars
7 lines

In this example, map1 is updated with the contents of map2. Any keys that correspond to a value in map1 are updated with the value from map2, and any new keys in map2 are added to map1.

Alternatively, you can use the | operator (pipe operator) to merge two dictionaries, which was introduced in Python version 3.9:

main.py
map1 = {"a": 1, "b": 2, "c": 3}
map2 = {"b": 4, "d": 5, "e": 6}

union_map = map1 | map2

print(union_map)  # Output: {'a': 1, 'b': 4, 'c': 3, 'd': 5, 'e': 6}
159 chars
7 lines

In this example, the | operator merges the two dictionaries into a new dictionary named union_map. The resulting dictionary contains all the key-value pairs from map1 and map2. If there are any keys that are present in both the maps, the value of the key in the second dictionary (map2) is used.

gistlibby LogSnag