合併兩個字典的 Python 程式


在本教程中,我們將學習如何在Python中合併兩個字典。我們來看看合併兩個字典的一些方法。

update() 方法

首先,我們將看到字典的內建方法 update() 進行合併。update() 方法返回 None 物件,將兩個字典合併為一個。我們來看看該程式。

示例

## initializing the dictionaries
fruits = {"apple": 2, "orange" : 3, "tangerine": 5}
dry_fruits = {"cashew": 3, "almond": 4, "pistachio": 6}
## updating the fruits dictionary
fruits.update(dry_fruits)
## printing the fruits dictionary
## it contains both the key: value pairs
print(fruits)

如果您執行以上程式,

輸出

{'apple': 2, 'orange': 3, 'tangerine': 5, 'cashew': 3, 'almond': 4, 'pistachio': 6}

** 運算子用於字典

** 有助於在一些特殊情況下解壓縮字典。在這裡,我們使用它來將兩個字典合併為一個。

示例

## initializing the dictionaries
fruits = {"apple": 2, "orange" : 3, "tangerine": 5}
dry_fruits = {"cashew": 3, "almond": 4, "pistachio": 6}
## combining two dictionaries
new_dictionary = {**dry_fruits, **fruits}
print(new_dictionary)

如果您執行以上程式,

輸出

{'cashew': 3, 'almond': 4, 'pistachio': 6, 'apple': 2, 'orange': 3, 'tangerine': 5}

我更喜歡第二種方法,而不是第一種方法。您可以使用上述任何一種方法來合併字典。這由您決定。

如果您對本教程有任何疑問,請在評論部分中提及。

更新於: 2019-08-27

556 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告