2011-11-01 60 views
3

所以我得到了元组内的元组,并且我想将它们变成一个key:value对。把元组的元组翻译成字典

((1L, 'I.T.'), (2L, 'Project Management'), (3L, 'Creative'), (4L, 'Programming'), (5L, 'Sales'), (6L, 'Administration'), (7L, 'AV'), (8L, 'Human Resources'), (9L, 'Conference Rooms'), (10L, 'Testing'), (11L, 'none')) 

我该如何去做这件事?

+0

可能重复[变换元组与dict(http://stackoverflow.com/questions/3553949/transform-tuple-to -dict)和[元组到字典列表](http://stackoverflow.com/questions/6522446/python-list-of-tuples-to-dictionary) –

回答

11

只需将它传递给dict构造函数!它可以采用任何可迭代的元组,并从中创建一个字典。

>>> x = ((1L, 'I.T.'), (2L, 'Project Management'), (3L, 'Creative'), (4L, 'Programming'), (5L, 'Sales'), (6L, 'Administration'), (7L, 'AV'), (8L, 'Human Resources'), (9L, 'Conference Rooms'), (10L, 'Testing'), (11L, 'none') 
>>> dict(x) 
{1L: 'I.T.', 2L: 'Project Management', 3L: 'Creative', 4L: 'Programming', 5L: 'Sales', 6L: 'Administration', 7L: 'AV', 8L: 'Human Resources', 9L: 'Conference Rooms', 10L: 'Testing', 11L: 'none'} 
+0

这很简单!谢谢! –

+0

反正有第一个值(1L等)成字符串吗?我不知道它是什么变量类型。 编辑:显然它是一个长整数。 –

+0

这是一个长整数,正如你可以通过其后缀'L'来判断。 – kindall

2

通过调用dict与你的元组作为参数:的

d = dict(t)