2013-02-02 227 views
1
dictionary = {} 

tabl = [('maint_id', 1003L), ('type', 'DB'), ('number', '102')] 
for i in tabl: 
    dictionary{i[0]:i[1]} 


print dictionary 

它给我的只是我的字典中最后一个键值对。它覆盖了所有的元素。什么是错的这个代码..任何帮助将元素附加到python字典中

+4

实际上,这ISN”有效的Python。你的意思是'字典= {我[0]:我[1]}'? –

回答

1

你想:

for i in tabl: 
    dictionary[i[0]] = i[1] 
+0

非常感谢。 –

+0

但有一个问题,订单变了。我需要它在数据输入相同的顺序在[13]:为我在表格中: ....:dictionary [i [0]] = i [1] ....: .... : 在[14]:DIC 字典字典 在[14]:字典 缺货[14]:{ '编号': '102', 'maint_id':1003L, '类型': 'DB'} –

+4

@just_in字典没有顺序。你需要使用['OrderedDict''](http://docs.python.org/2/library/collections.html#collections.OrderedDict)。 –

6

这是很容易:

dictionary = dict(tabl) 

如果为了事项:

from collections import OrderedDict 
dictionary = OrderedDict(tabl) 
+0

好点... :) – isedev