AppDividend
Latest Code Tutorials

Python Merge Operator in Dict Class with Example

0

To combine two dictionaries in Python, there are the following ways to do the job for you.

  1. Using dict.update() method.
  2. Using **kwargs

Using Python dict.update()

The dict.update() is a built-in Python method that updates a dictionary with the elements of another dictionary object or from an iterable value of key pair. The dict.update() method does not return a new dictionary. Instead, it modifies the existing dictionary.

dictA = {
    'astral': 45,
    'prince': 70,
    'deepak': 25
}

dictB = {
    'dixon': 17,
    'reliance': 23
}

dictA.update(dictB)
print(dictA)

Output

{'astral': 45, 'prince': 70, 'deepak': 25, 'dixon': 17, 'reliance': 23}

Using **kwargs

The special syntax **kwargs in python is used to pass the keyworded, variable-length argument list. We use the name kwargs with a double star.

dictA = {
    'astral': 45,
    'prince': 70,
    'deepak': 25
}

dictB = {
    'dixon': 17,
    'reliance': 23
}

combined_dict = {**dictA, **dictB}
print(combined_dict)

Output

{'astral': 45, 'prince': 70, 'deepak': 25, 'dixon': 17, 'reliance': 23}

It does not modify the original dictionary. Instead, it creates a new dictionary.

There is no specific inbuilt method to combine dictionaries in Python, but with the release of the Python 3.9 version, there is an operator that can combine the dictionaries with just one line of code. That operator is called the merge operator. Let’s find out how to use that.

Python Merge Operator

With Python 3.9, a new operator is introduced called merge operator ( | ) in the dict class. To combine the dictionaries in a single line of code, use the merge operator. Python merge operator is also called a union operator.

Syntax

merged_dict = dictA | dictB

Return Value

The merge operator returns the combined dictionary of input dictionaries.

Example

Let’s define two dictionaries and combine them using the merge operator.

dictA = {
    'astral': 45,
    'prince': 70,
    'deepak': 25
}

dictB = {
    'dixon': 17,
    'reliance': 23
}

combined_dict = dictA | dictB
print(combined_dict)

Output

{'astral': 45, 'prince': 70, 'deepak': 25, 'dixon': 17, 'reliance': 23}

You can see that the merge ( | ) operator works on two dict object operands and returns the merged dictionary.

The merge operator is not an in-place operator, which means it will create a new combined dictionary. The existing dictionaries won’t be modified.

That is it for the tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.