2013-11-24 99 views
1

python新手。我有一個包含一些信息的元組變量,我將它轉換成列表。當我使用我的for循環打印每個數據元素時,我得到了。如何從列表中獲取整數並在Python中構建哈希表?

for data in myTuple: 
    print list(data) 

['1', " This is the system 1 (It has been tested)."] 
['2', ' Tulip Database.'] 
['3', ' Primary database.'] 
['4', " Fourth database."] 
['5', " Munic database."] 
['6', ' Test database.'] 
['7', ' Final database.'] 

的問題是如何獲取的數(在單引號/雙引號),並將其存儲在下面的字典:

{’1’: 'This is the system 1 (It has been tested).', ’2’: 'Tulip Database.', ...} 

謝謝。

+1

'字典(myTuple)' – JBernardo

+0

在這種情況下,密鑰將是*字符串*除非轉換 - 也許他們應該是數字? – user2864740

回答

1

正如指出的JBernardo,y你可以使用內建的dict()

你也可以使用字典理解!

myTuple = [['1', " This is the system 1 (It has been tested)."], 
      ['2', ' Tulip Database.']] 
print {key:value for key, value in myTuple} 

輸出

{'1': ' This is the system 1 (It has been tested).', '2': ' Tulip Database.'} 
1

使用dict()

my_dict = dict(myTuple) 

演示:

>>> x = ([1, 'spam'], [2, 'foobar']) 
>>> dict(x) 
{1: 'spam', 2: 'foobar'} 

dict()當通過一個可迭代沒有這樣的事情(從help(dict)):

dict(iterable) -> new dictionary initialized as if via: 
    d = {} 
    for k, v in iterable: 
     d[k] = v 
+1

爲什麼?如果數據是可迭代的,則不需要這樣做 – JBernardo

+0

@JBernardo好點,'dict()'也適用於迭代器。 –