To merge two dictionaries in Python in a single expression, you can use the **
unpacking operator or the update()
method introduced in Python 3.9+. The **
operator allows combining dictionaries like this:
python
dict3 = {**dict1, **dict2}
This creates a new dictionary, with dict2
overwriting keys in dict1
if they conflict. Alternatively, in Python 3.9 and later, you can use the |
operator:
python
dict3 = dict1 | dict2
Both methods are concise and efficient for merging dictionaries. Note that neither approach modifies the original dictionaries; they create a new one.