Python 程序合并两个字典

编写一个 Python 程序来合并两个字典,并附带一个实际示例。有两种选项可以实现相同的功能。第一个选项使用内置的 update() 函数,另一个选项使用 **。

Python 程序合并两个字典示例

在此程序中,我们使用字典 update() 函数来使用 second_Dict 的值更新 first_Dict。

first_Dict = {1: 'apple', 2: 'Banana' , 3: 'Orange'}
second_Dict = { 4: 'Kiwi', 5: 'Mango'}
print("First : ", first_Dict)
print("Second : ", second_Dict)

first_Dict.update(second_Dict)
    
print("\nAfter Concatenating : ")
print(first_Dict)
using update() function

使用 ** 合并两个字典

这是在 Python 中合并的另一种方式。在此程序中,我们使用 dict 关键字来使用 first_Dict 和 ** second_Dict 创建一个新的 字典。在这里,** 允许您传递多个参数。

first_Dict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange'}
second_Dict = { 'k': 'Kiwi', 'm': 'Mango'}
print("First : ", first_Dict)
print("Second : ", second_Dict)

print("\nAfter Concatenating : ")
print(dict(first_Dict, **second_Dict) )
using ** operator

使用函数连接两个字典

此代码与上面相同。但是,使用 函数,我们将两个字典的连接逻辑分开了,在此 程序 中。

def Merge_Dictionaries(first, second):
    result = {**first_Dict, **second_Dict}
    return result

first_Dict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange'}
second_Dict = { 'k': 'Kiwi', 'm': 'Mango'}
print("First Dictionary: ", first_Dict)
print("Second Dictionary: ", second_Dict)

# Concatenate Two Dictionaries 
third_Dict = Merge_Dictionaries(first_Dict, second_Dict)

print("\nAfter Concatenating two Dictionaries : ")
print(third_Dict)
Program to Merge Two Dictionaries 3