在 Python 中合併兩個字典

Python 字典 是包含鍵值對中所有元素的數據結構。每個鍵值對將鍵與其關聯值進行映射。因此它也被稱為 Python 字典中的關聯數組。字典的所有元素都包含在大括號{}中。此外,我們在鍵-值對之間使用冒號(:)符號,將每個鍵與其關聯值分開。字典元素可以任意順序排列,在 Python 程序中動態變化。在本主題中,我們將學習如何使用 Python 字典的各種方法來合併兩個字典。

使用 for循環合併兩個字典

這裡我們使用 for循環 迭代第一個字典,同時向另一個字典添加條目來合併它們。

讓我們考慮一個使用 For 循環合併給定字典的程序。

福特契特. py


dict1 = { 'Alexandra' : 27,      # given the first dictionary in key-value pairs
            'Shelina Gomez' : 22,
            'James' : 29,
            'Peterson' : 30
                        } 
dict2 = {
            'Jasmine' : 19,      # given the second dictionary in key-value pairs
            'Maria' : 26,
            'Helena' : 30
}                        
print("Before merging the two dictionary ")
print("Dictionary No. 1 is : ", dict1) # print the dict1
print("Dictionary No. 1 is : ", dict2)  # print the dict2

dict3 = dict1.copy()  # Copy the dict1 into the dict3 using copy() method

for key, value in dict2.items():  # use for loop to iterate dict2 into the dict3 dictionary
    dict3[key] = value

print("After merging of the two Dictionary ")
print(dict3)    # print the merge dictionary

輸出:

Before merging the two dictionary
Dictionary No. 1 is :  {'Alexandra': 27, 'Selina Gomez': 22, 'James': 29, 'Peterson': 30}
Dictionary No. 1 is :  {'Jasmine': 19, 'Maria': 26, 'Helena': 30}
After merging of the two Dictionary
{'Alexandra': 27, 'Selina Gomez': 22, 'James': 29, 'Peterson': 30, 'Jasmine': 19, 'Maria': 26, 'Helena': 30}

使用 update()方法合併兩個字典

Python 字典中使用 update()方法用第二個字典的內容更新當前字典。使用 update()方法,我們可以避免創建第三個字典來存儲第一個字典元素,然後更新第二個字典元素。

讓我們考慮一個程序,在不創建第三個字典的情況下,合併 Python 中給定的字典。

更新 1.py


d1 = {'Actress ' : 'Jasmine Wiley',     
    'Cricketer' : 'Nicholas Pooran',
    'Basketball': 'Jordan',
    'Football' : 'Zindane'
}

# Defines the d2 dictionary 
d2 = {'Tennis ' : 'Maria',
    'Stadium  ' : 'Amsterdam',
    'Basketball' : 'Washington',
    'Actress' : 'Elizabeth'}

d1.update(d2) # append the d2 dictionary items into the d1 dictionary.
print( "Merge two dictionaries :")
print(d1) # print the merge dictionary 

輸出:

{'Actress ': 'Jasmine Wiley', 'Cricketer': 'Nicholas Pooran', 'Basketball': 'Washington', 'Football': 'Zindane', 'Tennis ': 'Maria', 'Stadium  ': 'Amsterdam', 'Actress': 'Elizabeth'}

使用函數合併 Python 中的兩個字典

讓我們考慮一個在 Python 中使用函數中的 update()方法合併給定字典的程序。

香水. py


def merge_twoDict(a, b): # define the merge_twoDict() function
    return (a.update(b)) # append the second dictionary (b) to the first dictionary (a) 

a = {'USA' : 'New York',
      'Jermany' : 'Jakarta',
      'England' : 'London' }
b = {
    'India' : 'Delhi',
    'Russia' : 'Russian',
    'Australia' : 'Sydney'
}          
merge_twoDict(a, b) # pass two dictionaries to merge_twoDict() function
print("Merged Dictionaries is : ")
print(a) # print the merge dictionaries 

輸出:

Merged Dictionaries is :
{'USA': 'New York', 'Germany': 'Jakarta', 'England': 'London', 'India': 'Delhi', 'Russia': 'Russian', 'Australia': 'Sydney'}

當兩個字典具有相同的鍵時,使用 update()方法合併兩個字典

讓我們考慮一個程序,當兩個字典包含相同的鍵時,使用 update()方法合併 Python 中的給定字典。

same dict . py


# Defines the d1 dictionary in key- value pairs
d1 = {    
    'Cricketer' : 'Nicholas Pooran',
    'Basketball': 'Jordan',
    'Football' : 'Zindane',
    'Actress' : 'Jasmine Wiley' 
    }

# Defines the d2 dictionary in key- value pairs
d2 = { 'Tennis' : 'Maria',
    'Stadium' : 'Amsterdam',
    'Basketball' : 'Washington',
    'Actress' : 'Elizabeth' }

d1.update(d2) # append the d2 dictionary items into the d1 dictionary.
print( "Merge two dictionaries :")
print(d1) # print the merge dictionary

輸出:

Merge two dictionaries :
{'Cricketer': 'Nicholas Pooran', 'Basketball': 'Washington', 'Football': 'Zindane', 'Actress': 'Elizabeth', 'Tennis': 'Maria', 'Stadium': 'Amsterdam'}

我們在兩個字典中都有兩個相同的鍵(女演員和籃球)。當我們執行更新方法時,第二個字典的最新值會覆蓋第一個字典的舊值。當 d1 字典被執行時,它打印華盛頓和伊麗莎白值為關鍵女演員和籃球而不是茉莉·威利和喬丹。

使用 Copy()和 Update()方法合併兩個字典

在這種方法中,我們使用 copy()函數複製第一個字典( d1 )元素的所有元素,然後將複製的數據分配到另一個字典(d3)中。之後,我們使用更新()功能用 d2 字典更新字典 d3 。

讓我們考慮一個使用 Python 中的複製和更新()方法合併給定字典的程序。

CopyUpdate.py


dict1 = {           
    'Student' : 'Butler',
    'Course' : 'Computer Science',
    'Address' : 'Los Angeles'
}

dict2 = {
    'Teacher' : 'Rosy',
    'Subject' : 'Computer Science'
}

# Use Copy() function to copy the dict1 into the dict3
dict3 = dict1.copy()
print("Before Merge")
print(dict3) # print dict3 dictionary

# use update() dictionary function to update the dict3 using the dict2.
dict3.update(dict2)

print("After Merge of the two Dictionary is : ", dict3)

輸出:

Before Merge
{'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles'}
After Merge of the two Dictionary is :  {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

使用**運算符-解包運算符合併兩個字典

解包操作符用於在一個表達式中組合兩個或多個字典,並將它們存儲在第三個字典中。

語法:


Res = { **dictF1, ** dictF2 }

讓我們考慮一個在 Python 中使用**運算符合併給定字典的程序。

打開包裝


dict1 = {           
    'Student' : 'Butler',
    'Course' : 'Computer Science',
    'Address' : 'Los Angeles'
}

dict2 = {
    'Teacher' : 'Rosy',
    'Subject' : 'Computer Science'
}

dict3 = {
    'Country' : 'England',
    'State' : 'California',
    'mob' : +3487434    
}

# Use ** operator or Unpack Operator
d5 = {**dict1, **dict2}
print("Merge two dictionaries", d5) # Merge two dictionaries

d4 = {
    **dict1, **dict2, **dict3 
    }
print("Merge more than two dictionaries", d4) # Merge multiples dictionaries

輸出:

Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}
Merge more than two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science', 'Country': 'England', 'State': 'California', 'mob': 3487434}

使用 dict()構造器合併兩個字典

一個 dict() 構造器方法類似於 Python 字典中的 copy() 和 update() 。一個 dict() 構造器將第一個字典元素複製到新字典中,然後跟隨一個 update()方法,用第二個字典的元素更新新字典。

讓我們考慮一個使用 Python 中 dict()方法合併給定字典的程序。

Dict.py


dict1 = {           
    'Student' : 'Butler',
    'Course' : 'Computer Science',
    'Address' : 'Los Angeles'
}

dict2 = {
    'Teacher' : 'Rosy',
    'Subject' : 'Computer Science'
}

# Use dict() constructor
d3 = dict(dict1)
print("Before Merge", d3)
d3.update(dict2)
print("Merge two dictionaries", d3) # Merge two dictionaries  

輸出:

Before Merge {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles'}
Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

使用 dict()構造器和**kwargs 合併兩個字典

這是 dict()構造器的一個快捷方法,它使用 kwargs (**)運算符在 dict()方法的幫助下將一個字典映射到另一個字典。

語法:


D3 = dict(dict1, **dict)

讓我們考慮一個使用 Python 中的 dict()構造器和**kwargs 運算符合併兩個字典的程序。

Kwarg.py


dict1 = {           
    'Student' : 'Butler',
    'Course' : 'Computer Science',
    'Address' : 'Los Angeles'
}

# Second dictionary is:
dict2 = {
    'Teacher' : 'Rosy',
    'Subject' : 'Computer Science'
}

# Use dict() constructor
d3 = dict(dict1, **dict2)

print("Merge two dictionaries", d3) # Merge two dictionaries

輸出:

Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

使用集合-鏈接映射功能合併兩個字典

ChainMap 是返回單個字典的多個字典的集合。與 update()方法相比,創建新字典和運行多個文件是一種更快的方法。為了合併 Python 中的兩個字典,我們需要從集合中導入鏈圖。在 ChainMap()函數中,我們傳遞兩個字典作為參數,返回 ChainMap 實例,使用 dict()構造器映射字典,合併字典。

讓我們考慮一個使用 Python 中的 ChainMap 函數合併兩個字典的程序。

Chain_map.py


dict1 = {           
    'Student' : 'Butler',
    'Course' : 'Computer Science',
    'Address' : 'Los Angeles'
}
dict2 = {
    'Teacher' : 'Rosy',
    'Subject' : 'Computer Science'
}
from collections import ChainMap  # import the ChainMap from collections

# Use ChainMap() constructor
d3 = dict(ChainMap(dict1, dict2)) # passes two parameters as an argument

print("Merge two dictionaries", d3) # Merge two dictionaries

輸出:

Merge two dictionaries {'Teacher': 'Rosy', 'Subject': 'Computer Science', 'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles'}

使用 itertools – chain()方法合併兩個字典

它生成一個迭代字典,從第一個可迭代字典返回一個元素,直到它完成。然後,它前進到下一個可在字典中進一步執行的條目。因此,它將連續序列表示為單個序列。

語法:


itertools.chain( *iterables )

讓我們考慮一個使用 Python 中的鏈式函數合併兩個字典的程序。

Chain.py


dict1 = {           
    'Student' : 'Butler',
    'Course' : 'Computer Science',
    'Address' : 'Los Angeles'
}
dict2 = {
    'Teacher' : 'Rosy',
    'Subject' : 'Computer Science'
}
from itertools import chain  # import the chain() function from itertools

# Use ChainMap() constructor
d3 = dict(chain(dict1.items(), dict2.items())) # passes two parameters as an argument

print("Merge two dictionaries", d3) # Merge two dictionaries

輸出:

Merge two dictionaries {'Student': 'Butler', 'Course': 'Computer Science', 'Address': 'Los Angeles', 'Teacher': 'Rosy', 'Subject': 'Computer Science'}

使用 merge ( |)運算符合併兩個字典

它是一個 merge (|)運算符,用於合併 Python 中的兩個字典。Python 3.9 在 dict 類中引入了 merge ( |)運算符。

語法:


dict1 |= dict2

讓我們編寫一個程序,使用 merge 運算符(|)在 Python 中合併這兩個字典。

merge.py


def merge(dict1, dict):
    result = dict1 | dict2 # use merge operator (|)
    return result

dict1 = {'A' : 'Apple', 'B' : 'Ball', 'C' : 'Cat' } # define dict1
dict2 = {'D' : 'Dog', 'E' : 'Elephant', 'F' : 'Fish' } # define dict2
dict3 = merge(dict1, dict2) # call merge() function
print (dict3)    # print dict3

輸出:

{'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephant', 'F': 'Fish'}

原創文章,作者:LK1R1,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/128919.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
LK1R1的頭像LK1R1
上一篇 2024-10-03 23:25
下一篇 2024-10-03 23:25

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29

發表回復

登錄後才能評論