在Python中组合字典的方法(3种方法)

803 阅读2分钟

在 Python 中,字典有一个键值对数据结构。在很多情况下,组合或合并两个或多个字典是必不可少的。在这篇文章中,你将看到如何结合两个或多个字典。

有很多方法可以组合字典。我们将了解以下三种在Python中组合字典的方法:

  1. 使用 dict.update() 方法
  2. 使用 unpack(**) 操作符
  3. 使用 | 操作符

Python 合并 dicts

要在Python中组合dict,可以使用dict.update()方法。dict.update() 是一个内置的 Python 方法,它用另一个字典中的项目更新字典。

如果我们有两个字典,并且我们想合并它们,那么我们将在 dictionary 2 上调用 update() 方法,并将 dictionary 1 作为参数传递。它返回None,但是 dictionary 2 现在成为一个合并的 dictionary。

dict.update()的语法

dict.update([iterable])

参数

update() 方法接受一个迭代器,它可以是 dictionary,也可以是任何其它迭代器。

返回值

update() 方法返回None作为输出。

合并两个字典的实现

让我们声明两个字典并使用update()方法将它们合并:

book = {"author": "J K Rowling", "book_name": "Harry Potter"}
movie = {"director": "Chris Columbus", "movie_name": "Sorcerers Stone"}

merged_dict = movie.update(book)

print(merged_dict)
print("The Merged Dictionary", movie)

输出

None

The Merged Dictionary {'director': 'Chris Columbus', 'movie_name': 'Sorcerers Stone', 
                       'author': 'J K Rowling', 'book_name': 'Harry Potter'}

你可以看到两个字典已经被合并成一个字典,update()方法的返回值是None。

所以这是你可以合并字典的一种方法。

使用 ** 操作符来合并 dictionary

你可以使用单个表达式** ,它允许你直接使用 dictionary 向一个函数传递多个参数。

在这个例子中,我们将使用**表达式合并两个字典。

book = {"author": "J K Rowling", "book_name": "Harry Potter"}
movie = {"director": "Chris Columbus", "movie_name": "Sorcerers Stone"}

merged_dict = {**book, **movie}

print(merged_dict)

输出

{'author': 'J K Rowling', 'book_name': 'Harry Potter', 
 'director': 'Chris Columbus', 'movie_name': 'Sorcerers Stone'}

你可以看到,这两个字典已经被合并了。

使用 | 操作符来合并字典

使用 | 操作符来合并两个字典,这是最简单的方法之一:

book = {"author": "J K Rowling", "book_name": "Harry Potter"}
movie = {"director": "Chris Columbus", "movie_name": "Sorcerers Stone"}

merged_dict = book | movie

print(merged_dict)

输出

{'author': 'J K Rowling', 'book_name': 'Harry Potter', 
 'director': 'Chris Columbus', 'movie_name': 'Sorcerers Stone'}

在Python中合并多个字典

要在Python中合并多个字典,使用 | 操作符:

book = {"author": "J K Rowling", "book_name": "Harry Potter"}
movie = {"director": "Chris Columbus", "movie_name": "Sorcerers Stone"}
game = {"studio": "Warner Bros", "game_name": "Hogwarts Legacy"}

merged_dict = book | movie | game

print(merged_dict)

输出

{'author': 'J K Rowling', 'book_name': 'Harry Potter', 
 'director': 'Chris Columbus', 'movie_name': 'Sorcerers Stone', 
 'studio': 'Warner Bros', 'game_name': 'Hogwarts Legacy'}

你可以看到,它只用一行代码就合并了三个字典。

本教程就到此为止。

参见

Python 合并操作符

在Python中合并两个列表

Python更新操作符