How do I merge dicts in Python with examples?

Merging dictionaries in Python can be accomplished using several methods. Here are some common techniques:

Using the Update Method

The `update()` method modifies a dictionary in place by adding elements from another dictionary.

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

Using the Merge Operator (Python 3.9+)

In Python 3.9 and later, you can use the merge (`|`) operator to combine 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}

Using Dictionary Comprehension

You can also use dictionary comprehension to merge dictionaries.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged_dict = {k: v for d in [dict1, dict2] for k, v in d.items()} print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}

merge dicts Python dictionary update method merge operator dictionary comprehension