split a map into two maps in python

If you have a dictionary or map, and you want to split it into two separate dictionaries, you can use the deepcopy method from the copy module. Here is an example:

main.py
import copy

# original map
map1 = {
    'a': 1, 
    'b': 2, 
    'c': 3,
    'd': 4
}

# make a deep copy of the original map
map2 = copy.deepcopy(map1)

# remove some keys from map1
keys_to_remove = ['a', 'b']
for key in keys_to_remove:
    map1.pop(key)

# remove some keys from map2
keys_to_remove = ['c', 'd']
for key in keys_to_remove:
    map2.pop(key)

print(map1)  # {'c': 3}
print(map2)  # {'a': 1, 'b': 2}
418 chars
26 lines

In this example, copy.deepcopy is used to make a copy of the original map, to ensure that the two resulting maps are completely independent of each other. Then, keys are removed from each map independently.

gistlibby LogSnag