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

时间:2019-03-23 13:19:24

标签: python python-3.x dictionary tuples dictionary-comprehension

我有一个元组,其中包含多个子元组,固定长度为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...

2 个答案:

答案 0 :(得分:3)

您应该能够:

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

更加简单,您可以执行x = dict(main_tuple)

答案 1 :(得分:3)

您可以改用dict构造函数:

dict(main_tuple)