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]
但这会得到不正确的结果(我无法理解它们).我怎么能得到如上所述的输出?
解决方法:
使用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'
'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')])
标签:python,list,dictionary