您的位置:

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