如何在不创建任何新变量的情况下在字典理解中解压缩元组的值?

How do I unpack the values of a tuple in a dictionary comprehension without creating any new variables?

我有一个包含多个子元组的元组,固定长度为 2,每个子元组有两个字符串值。

注意:这些子元组的长度和值类型永远不会改变。

我想在字典理解中使用子元组,如下所示:

{sub_tuple for sub_tuple in main_tuple}

问题是,我得到:

{(w, x), (y, z)}

而不是:

{w: x, y: z}

如何在不创建任何额外变量的情况下让它工作?

例如,我如何避免做这样的事情:

x = {}
for sub_tuple in main_tuple:
  x[sub_tuple[0]] = sub_tuple[1]
# do whatever with x...

你应该可以做到:

x = {
    key: value
    for key, value in main_tuple
}

更简单的,你可以x = dict(main_tuple)

您可以改用 dict 构造函数:

dict(main_tuple)