2013-05-13 68 views
3

我具有相同的长度和字典的2所列出如何增加对应从列表来蟒字典键元素和值分别

list1 = ['hello', 'goodbye', 'no', 'yes', 'if you say so'] 
list2 = ['a', 'b', 'c', 'd; e; f', 'g'] 
listDict = {} 

我想对应的值作为键和值分别添加,因此字典的输出应该是这样的(和顺序应该保持不变)

listDict = {'hello':'a', 'goodbye':'b', 'no':'c', 'yes':'d; e; f', 'if you say so':'g'} 

我试图

for words in list1: 
    for letters in list2: 
     listDict[words]=[letters] 

但这给出了不正确的结果(我无法理解它们)。我怎么能得到如上所述的输出?

回答

4

使用zip()

>>> list1 = ['hello', 'goodbye', 'no', 'yes', 'if you say so'] 
>>> list2 = ['a', 'b', 'c', 'd; e; f', 'g'] 
>>> dict(zip(list1,list2)) 
{'if you say so': 'g', 'yes': 'd; e; f', 'hello': 'a', 'goodbye': 'b', 'no': 'c'} 

'yes' 'if you say so'被认为是一个字符串,用,将它们分开:

>>> 'yes' 'if you say so' 
'yesif you say so' 

使用collections.OrderedDict中保持秩序:

>>> from collections import OrderedDict 
>>> OrderedDict(zip(list1,list2)) 

OrderedDict([('hello', 'a'), ('goodbye', 'b'), ('no', 'c'), ('yes', 'd; e; f'), ('if you say so', 'g')]) 
+0

我需要保持它的顺序,但是因为我必须以相同的顺序打印键和值...所以'你好':'a','再见':'b'等等.. – user2353608 2013-05-13 10:51:54

+0

@ user2353608我更新了我的解决方案。 – 2013-05-13 10:54:14

+0

对不起,我是初学者,但答案怎么不再像字典?我希望它看起来像{'hello':'a','goodbye':'b'...} – user2353608 2013-05-13 11:02:37

1
list1 = ['hello', 'goodbye', 'no', 'yes' 'if you say so'] 
list2 = ['a', 'b', 'c', 'd; e; f', 'g']  
listDict = dict(zip(list1, list2)) 
相关问题