In this article we will create a Python function which will merge two dictionaries using the Dict Union operator.

The Dict Union operator will only merge the key and value pair with a unique key’s name, which means if there are two keys with the same name in the same dictionary, only the last key in the dictionary will be merged. If the same key appears in both dictionaries, then the key in the second dictionary will be merged into this Dict union.

After the merger of two dictionaries, the function will change the value of the key if the third optional argument has tuples in it which contain the key and value to be changed.

def merged(k1, k2, front):

    k3 = k1 | k2
    if front != []:
        k3 |= front
    return k3

Now let us try out a few examples:-

d = {'shoe': 1, 'slipper': 2, 'boot': 3, 'shoe':7}
l = {'shirt': 3, 'dress': 1, 'shoe':4}

print(merged(d, l, [('shirt', 5)]))
{'shoe': 4, 'slipper': 2, 'boot': 3, 'shirt': 5, 'dress': 1}
d = {'shoe': 1, 'slipper': 2, 'boot': 3, 'shoe':7}
l = {'shirt': 3, 'dress': 1}

print(merged(d, l, [('shirt', 5)]))
{'shoe': 7, 'slipper': 2, 'boot': 3, 'shirt': 5, 'dress': 1}
d = {'shoe': 1, 'slipper': 2, 'boot': 3, 'shoe':7}
l = {'shirt': 3, 'dress': 1}

print(merged(d, l, [('shirt', 5), ('shoe', 3)]))
{'shoe': 3, 'slipper': 2, 'boot': 3, 'shirt': 5, 'dress': 1}
d = {'shoe': 1, 'slipper': 2, 'boot': 3, 'shoe':7}
l = {'shirt': 3, 'dress': 1}

print(merged(d, l, []))
{'shoe': 7, 'slipper': 2, 'boot': 3, 'shirt': 3, 'dress': 1}

What is your thought about this? Leave your comment with your own solution in the comment box under this post 🙂

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *