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-hk/n/128919.html