Merging or Concatenating Two Dictionaries in Python (original) (raw)

Last Updated : 1 Nov, 2025

Given two dictionaries, the task is to merge them into a single dictionary that contains all key-value pairs. For example:

**Input: d1 = {'x': 1, 'y': 2} and d2 = {'y': 3, 'z': 4}
**Output: {'x': 1, 'y': 3, 'z': 4}

Here, both dictionaries are combined. If the same key exists in both, the value from the second dictionary replaces the value from the first. Let’s explore different methods to merge or concatenate two dictionaries in Python.

Using | Operator (Python 3.9+)

| operator introduced in Python 3.9 can be used to merge dictionaries. It creates a new dictionary without modifying the original dictionary.

Python `

d1 = {'x': 1, 'y': 2} d2 = {'y': 3, 'z': 4}

d3 = d1 | d2 print(d3)

`

**Output:

{'x': 1, 'y': 3, 'z': 4}

**Explanation:

Using Dictionary Unpacking (**)

Dictionary unpacking allows us to merge dictionaries into a new one.

Python `

d1 = {'x': 1, 'y': 2} d2 = {'y': 3, 'z': 4}

d3 = {**d1, **d2} print(d3)

`

Output

{'x': 1, 'y': 3, 'z': 4}

**Explanation:

Using update()

update()method can be used to merge dictionaries. It modifies one dictionary by adding or updating key-value pairs from another.

Python `

d1 = {'x': 1, 'y': 2} d2 = {'y': 3, 'z': 4} d1.update(d2) print(d1)

`

Output

{'x': 1, 'y': 3, 'z': 4}

**Explanation:

**Note: This method modifies the original dictionary (**d1).

Using Loop

We can use a loop (for loop) to merge dictionaries.

Python `

d1 = {'x': 1, 'y': 2} d2 = {'y': 3, 'z': 4}

d3 = d1.copy() for key, value in d2.items(): d3[key] = value

print(d3)

`