2011-11-01 35 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)