我有一个元组,其中包含多个子元组,固定长度为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...
答案 0 :(得分:3)
您应该能够:
x = {
key: value
for key, value in main_tuple
}
更加简单,您可以执行x = dict(main_tuple)
答案 1 :(得分:3)
您可以改用dict构造函数:
dict(main_tuple)