Union of dictionary objects in Python
In this we can create a Union of two dictionaries using several methods, depending on your Python versions,This combined dictionary includes all key-value pairs from the original dictionaries. If there are duplicate keys, the values from the latter dictionary in the operation will overwrite the values from the former. Here are common methods to achieve this:
Using Python 3.9 and later
in this Python 3.9 we will be using the ‘|’ operator to merge dictionaries ,
dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} union_dict = dict1 | dict2 print(union_dict) Output: {'a': 1, 'b': 3, 'c': 4}
OUTPUT:
{ 'a' : 1, 'b' : 3, 'c' : 4}
Merge dictionaries without duplicates in
Using Python 3.5 and later
n Python 3.5 and later, we will use this **** unpacking operator to merge dictionaries , In Python 3.5 and later, one of the efficient ways to merge dictionaries is by using the dictionary unpacking feature with the ** operator. This method allows you to combine multiple dictionaries into a new one in a concise and readable manner.
dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} union_dict = {**dict1, **dict2} print(union_dict)
OUTPUT:
{'a': 1, 'b': 3, 'c': 4}
Using custom function
we can also define a custom function to merge dictionaries Explanation: This function first creates a copy of dict1 to avoid modifying the original. It then updates this copy with the key-value pairs from dict2 and returns the merged dictionary.
def merge_dicts(dict1, dict2): result = dict1.copy() result.update(dict2) return result dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} union_dict = merge_dicts(dict1, dict2) print(union_dict)
OUTPUT:
{'a': 1, 'b': 3, 'c': 4}
Leave a Reply