Python 字典是一种包含所有元素的键-值对数据结构。每个键-值对将键映射到其相关联的值。因此,它也被称为 Python 字典的关联数组。字典的所有元素都包含在花括号 {} 内。此外,在键-值对之间,我们使用冒号 (:) 符号,用于将每个键与其关联值分隔开来。字典元素可以以任何顺序排列,并且可以在Python 程序中动态更改。在本主题中,我们将学习如何使用 Python 字典的各种方法合并两个字典。

154.png

使用 for 循环合并两个字典

在这里,我们使用一个for 循环,它遍历第一个字典并同时将条目添加到另一个字典中以进行合并。

让我们考虑一个程序,使用For循环合并给定的字典。

forDict.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() 方法合并两个字典

update() 方法用于在 Python 字典中更新当前字典的内容。使用 update() 方法,我们可以避免创建一个第三个字典来存储第一个字典的元素,然后再更新第二个字典的元素。

让我们考虑一个程序,在不创建第三个字典的情况下合并给定的字典。

Update1.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 中使用函数中的 update() 方法来合并给定的字典。

proFun.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() 方法合并两个具有相同键的字典

让我们考虑一个程序,在 Python 中使用 update() 方法合并两个具有相同键的字典时的情况。

sameDict.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'}

在两个字典中都具有相同键(女演员和篮球)的情况下,当我们执行 update 方法时,第二个字典的最新值将覆盖第一个字典的旧值。在执行 d1 字典时,它将为键 女演员篮球 打印 WashingtonElizabeth 的值,而不是 Jasmine Wiley 和 Jordan。

使用 Copy() 和 Update() 方法合并两个字典

在此方法中,我们使用 copy() 函数复制第一个字典(d1)的所有元素,然后将复制的数据分配给其他字典(d3)。然后,我们使用 update() 函数将字典 d3 更新为字典 d2,以便合并字典。

让我们考虑一个程序,在 Python 中使用 copy 和 update() 方法合并给定的字典。

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 中使用 ** 运算符合并两个字典。

Unpack.py

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() 构造函数将第一个字典的元素复制到新字典中,然后使用第二个字典的元素更新新字典。

让我们考虑一个程序,在 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'}

使用 Collections - ChainMap 函数合并两个字典

ChainMap 是多个字典的集合,返回一个单一的字典。它是比 update() 方法更快地创建一个新字典并运行多个文件的方法。要合并两个字典,我们需要从 collections 中导入 ChainMap。在 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() 方法合并两个字典

chain() 方法创建一个迭代字典,从第一个可迭代字典中返回一个元素,直到完成为止。然后,它继续执行下一个可迭代字典,以在一个字典中进行进一步的操作。因此,它将连续的序列表示为单个序列。

语法:

itertools.chain( *iterables )  

让我们考虑一个程序,在 Python 中使用 chain 函数合并两个字典。

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'}

使用合并 ( | ) 运算符合并两个字典

合并 (|) 运算符用于在 Python 中合并两个字典。Python 3.9 引入了 dict 类中的合并 (|) 运算符。

语法:

dict1 |= dict2 

让我们编写一个程序,在 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'}

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程