3

I have 2 lists of the same length and a dictionary

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

I want to add the corresponding values as keys and values respectively, so the output of the dictionary should be like this (and order should stay the same)

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

I tried

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

but that gives incorrect results (I can't understand them). How could i get the output as described above?

user2353608
  • 209
  • 1
  • 2
  • 7

2 Answers2

4

use 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' is considered as a single string, use , to separate them:

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

Use collections.OrderedDict to preserve order:

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

OrderedDict([('hello', 'a'), ('goodbye', 'b'), ('no', 'c'), ('yes', 'd; e; f'), ('if you say so', 'g')])
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
1
list1 = ['hello', 'goodbye', 'no', 'yes' 'if you say so']
list2 = ['a', 'b', 'c', 'd; e; f', 'g']    
listDict = dict(zip(list1, list2))
jvallver
  • 1,962
  • 2
  • 10
  • 19