简体   繁体   English

如何将一对元组转换成字典?

[英]How to convert a pair of tuples into a dictionary?

I have the following data set: 我有以下数据集:

data=[(('a','b','c'),('x','y','z'))]

How can I convert this into dictionary such that there is mapping as shown below: 我如何将其转换为字典,以使映射如下所示:

d={'a':'x','b':'y','c':'z'}

由于我们正在玩代码高尔夫球:)

dict(zip(*data[0]))

You can simply zip the two tuple and operate using dict . 您可以简单地zip两个tuple并使用dict进行操作。

In [189]: dict(zip(data[0][0], data[0][1]))
Out[189]: {'a': 'x', 'b': 'y', 'c': 'z'}
data=[(('a','b','c'),('x','y','z'))]
dictVal = {}

for key, val in zip(data[0][0], data[0][1]):
   dictVal[key] = val

You can do so with a dictionary comprehension. 您可以通过字典理解来做到这一点。

d = {key:value for key in data[0][0] for value in data[0][1]}

You can use dictionary comprehensions like this with multiple variables and for loops to make a dictionary from two different iterables. 您可以将这样的字典理解与多个变量一起使用,并使用for循环从两个不同的可迭代对象中创建字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM