
Python Concatenate Dictionary
The Python can concatenate or merge dictionaries using various techniques depending on your Python version. Here, I’ll show you several methods to concatenate dictionaries in Python:
Method 1: Using the update()
Method
You can use the update()
method to add items from one dictionary to another. If keys in the second dictionary already exist in the first one, their values will be updated.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2) # This will merge dict2 into dict1
print(dict1)
Output:
{'a': 1, 'b': 3, 'c': 4}
Method 2: Using Dictionary Comprehension (Python 3.5+)
You can use a dictionary comprehension to concatenate dictionaries in a single line of code.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {key: value for d in [dict1, dict2] for key, value in d.items()}
print(merged_dict)
Output:
{'a': 1, 'b': 3, 'c': 4}
Method 3: Using the **
Unpacking Operator (Python 3.5+)
You can use the **
unpacking operator to merge two dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
Output:
{'a': 1, 'b': 3, 'c': 4}
Method 4: Using the collections.ChainMap
(Python 3.3+)
The collections.ChainMap
class allows you to combine multiple dictionaries into a single “chain” of dictionaries.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict(ChainMap(dict1, dict2))
print(merged_dict)
Output:
{'a': 1, 'b': 2, 'c': 4}
Choose the method that best suits your needs and coding style. These methods allow you to concatenate dictionaries in Python efficiently and effectively.