将元组列表转换为 Python 中的字典

在 Python 中将元组列表转换为字典

Convert a list of tuples to a dictionary in Python

使用dict该类将元组列表转换为字典,例如
my_dict = dict(list_of_tuples). 该类dict可以传递一个元组列表并返回一个新字典。

主程序
list_of_tuples = [('one', 1), ('two', 2), ('three', 3)] my_dict = dict(list_of_tuples) # 👇️ {'one': 1, 'two': 2, 'three': 3} print(my_dict)

我们使用dict类将元组列表转换为字典。

请注意,此方法仅在您的元组每个包含 2 个元素(一个键和一个值)时才有效。

或者,您可以使用dict理解。

使用字典理解将元组列表转换为字典,例如
my_dict = {tup[0]: tup[1] for tup in list_of_tuples}. dict comprehension 将遍历列表,允许我们将每个键值对设置为特定的元组元素。

主程序
list_of_tuples = [('one', 1), ('two', 2), ('three', 3)] my_dict = {tup[0]: tup[1] for tup in list_of_tuples} # 👇️ {'one': 1, 'two': 2, 'three': 3} print(my_dict)

字典理解与列表理解非常相似。

他们对字典中的每个键值对执行一些操作,或者选择满足条件的键值对的子集。

在每次迭代中,我们将字典键设置为元组中的第一个元素,并将相应的值设置为第二个元素。

这种方法比使用dict类灵活得多,因为它不假定列表中的元组只有 2 个元素——一个键和一个值。

主程序
list_of_tuples = [(1, 'one', 'a'), (1, 'two', 'b'), (3, 'three', 'c')] my_dict = {tup[1]: tup[0] for tup in list_of_tuples} # 👇️ {'one': 1, 'two': 2, 'three': 3} print(my_dict)

如果你的元组只包含两个元素,你也可以使用解包。

主程序
list_of_tuples = [('one', 1), ('two', 2), ('three', 3)] my_dict = {key: value for key, value in list_of_tuples} print(my_dict)

As opposed to the dict class, this approach would also work if the first
element in each tuple is the value.

main.py
list_of_tuples = [(1, 'one'), (2, 'two'), (3, 'three')] my_dict = {key: value for value, key in list_of_tuples} print(my_dict) # 👉️ {'one': 1, 'two': 2, 'three': 3}
When unpacking, make sure to declare exactly as many variables as there are items in the iterable.

When unpacking from a tuple, each variable declaration counts for a single item.

Make sure to declare exactly as many variables as there are items in the tuple.

main.py
key, value = ('one', 1) print(key) # 👉️ one print(value) # 👉️ 1

If you try to unpack more or fewer values than there are in the tuple, you would
get an error.

main.py
# ⛔️ ValueError: too many values to unpack (expected 2) key, value = ('one', 1, 'a')
We declare 2 variables, but the tuple contains 3 items. The inconsistency between the number of variables and items in the tuple causes a ValueError.

If you don’t need to store a certain value, use an underscore for the variable’s
name.

main.py
key, value, _ = ('one', 1, 'a') print(key) # 👉️ one print(value) # 👉️ 1

当您对变量名称使用下划线时,您向其他开发人员表明该变量只是一个占位符。

解包值时,您可以根据需要使用尽可能多的下划线。