深度阅读

How to merge two dictionaries in Python?

作者
作者
2023年08月22日
更新时间
13.53 分钟
阅读时间
0
阅读量

There are several ways to merge two dictionaries in Python, depending on your specific use case. Here are a few examples:

  1. Using the update() method: You can use the update() method to add all the key-value pairs from one dictionary to another:
dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key3': 'value3', 'key4': 'value4'}
dict1.update(dict2)

After this code block, dict1 will be the merged dictionary, containing all the key-value pairs from both dict1 and dict2.
2. Using the ** operator: You can use the ** operator to unpack the values of two dictionaries and create a new, merged dictionary:

dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key3': 'value3', 'key4': 'value4'}
merged_dict = {**dict1, **dict2}

After this code block, merged_dict will be a new dictionary containing all the key-value pairs from both dict1 and dict2.
3. Using the | operator: In Python 3.9 or newer, you can use the | operator to merge two dictionaries, like this:

dict1 = {'key1': 'value1', 'key2': 'value2'}
dict2 = {'key3': 'value3', 'key4': 'value4'}
merged_dict = dict1 | dict2

After this code block, merged_dict will be a new dictionary containing all the key-value pairs from both dict1 and dict2.

Choose the method that suits your specific use case and Python version.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。