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
  • 229
  • 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
  • 244,495
  • 58
  • 464
  • 504
  • I need to keep it in order though as I have to later print the keys and values in the same order... so 'hello':'a', 'goodbye':'b' and so on.. – user2353608 May 13 '13 at 10:51
  • Sorry I'm beginner, but how come the answer doesn't look like a dictionary anymore? I want it to look like {'hello': 'a', 'goodbye':'b' .... } – user2353608 May 13 '13 at 11:02
  • @user2353608 It's a subclass of dictionary that preserves order, it's just a representation. – Ashwini Chaudhary May 13 '13 at 11:03
1
list1 = ['hello', 'goodbye', 'no', 'yes' 'if you say so']
list2 = ['a', 'b', 'c', 'd; e; f', 'g']    
listDict = dict(zip(list1, list2))
jvallver
  • 2,230
  • 2
  • 11
  • 20