在 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类将元组列表转换为字典。
或者,您可以使用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.
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 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.
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.
# ⛔️ ValueError: too many values to unpack (expected 2) key, value = ('one', 1, 'a')
ValueError
.If you don’t need to store a certain value, use an underscore for the variable’s
name.
key, value, _ = ('one', 1, 'a') print(key) # 👉️ one print(value) # 👉️ 1
当您对变量名称使用下划线时,您向其他开发人员表明该变量只是一个占位符。
解包值时,您可以根据需要使用尽可能多的下划线。