How to Concat Dictionary in Python
To concatenate dictionaries in Python, you can use the update() function, the ** operator, or the items() function along with the dict() function.
The following examples show how to concatenate dictionaries in Python using different methods.
Using update() Function
We can use the update() function to concatenate dictionaries.
Suppose we have the following dictionaries:
# Declare dictionaries
d1 = {'A': 1, 'B': 2}
d2 = {'C': 3}
# Concatenate dictionaries
d1.update(d2)
# Show concatenated dictionary
print("Concatenated dictionary is:", d1)
Output: 👇️
Concatenated dictionary is: {'A': 1, 'B': 2, 'C': 3}
In this example, we use the update() function to concatenate d2 into d1. The output shows the concatenated dictionary.
Using ** Operator
We can use the ** operator to concatenate dictionaries.
Suppose we have the following dictionaries:
# Declare dictionaries
d1 = {'A': 1, 'B': 2}
d2 = {'C': 3}
# Concatenate dictionaries
dict_ = {**d1, **d2}
# Show concatenated dictionary
print("Concatenated dictionary is:", dict_)
Output: 👇️
Concatenated dictionary is: {'A': 1, 'B': 2, 'C': 3}
In this example, we use the ** operator to concatenate d1 and d2 into a new dictionary dict_. The output shows the concatenated dictionary.
Using items() & dict() Function
We can use the items() function and the dict() function to concatenate dictionaries.
Suppose we have the following dictionaries:
# Declare dictionaries
d1 = {'A': 1, 'B': 2}
d2 = {'C': 3}
# Concatenate dictionaries
dict_ = dict(list(d1.items()) + list(d2.items()))
# Show concatenated dictionary
print("Concatenated dictionary is:", dict_)
Output: 👇️
Concatenated dictionary is: {'A': 1, 'B': 2, 'C': 3}
In this example, we use the items() function to convert the dictionaries d1 and d2 into lists of key-value pairs, concatenate these lists, and then convert the result back into a dictionary using the dict() function. The output shows the concatenated dictionary.
Conclusion
We can use the update() function, the ** operator, and the items() function along with the dict() function to concatenate dictionaries in Python. These methods provide a convenient way to merge dictionaries.