How do I concatenate dicts in Python with examples?

In Python, you can concatenate dictionaries in several ways. Here are some common methods:

1. Using the `update()` method:

The `update()` method can be used to add elements from one dictionary to another.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1.update(dict2) print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}

2. Using the `{**d1, **d2}` syntax:

This syntax allows you to unpack dictionaries into a new dictionary.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} combined = {**dict1, **dict2} print(combined) # Output: {'a': 1, 'b': 3, 'c': 4}

3. Using the `|` operator (Python 3.9 and later):

Starting from Python 3.9, you can use the `|` operator to merge dictionaries.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} combined = dict1 | dict2 print(combined) # Output: {'a': 1, 'b': 3, 'c': 4}

Python Concatenate Dictionaries Python Merge Dicts Update Dicts Python Dictionary Python 3.9