Python 程式將兩個字典組合成一個字典


當需要將兩個字典連線成一個實體時,可以使用“update”方法。

字典是“鍵值”對。

下面演示了這一方法 −

示例

 現場演示

my_dict_1 = {'J':12,'W':22}
my_dict_2 = {'M':67}
print("The first dictionary is :")
print(my_dict_1)
print("The second dictionary is :")
print(my_dict_2)
my_dict_1.update(my_dict_2)
print("The concatenated dictionary is :")
print(my_dict_1)

輸出

The first dictionary is :
{'J': 12, 'W': 22}
The second dictionary is :
{'M': 67}
The concatenated dictionary is :
{'J': 12, 'W': 22, 'M': 67}

說明

定義了兩個字典,並顯示在控制檯上。 

  • 在第一個字典中呼叫“update”方法,同時將第二個字典作為引數傳遞。 
  • 這將有助於連線字典。 
  • 它顯示在控制檯上。

更新於: 2021-03-12

2K+ 瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.