[Tutor] two lists to keys and values in dictionary

Gregor Lingl glingl@aon.at
Mon, 12 Aug 2002 20:20:02 +0200


Doug.Shawhan@gecits.ge.com schrieb:

>Okay, I have two lists:
>
>l1=['wicky', 'wacky', 'woo']
>l2=['hip', 'hop', 'hoo']
>
>  
>
 >>> l1=['wicky', 'wacky', 'woo']
 >>> l2=['hip', 'hop', 'hoo']
 >>> zip(l1,l2)
[('wicky', 'hip'), ('wacky', 'hop'), ('woo', 'hoo')]
 >>> pairs = zip(l1,l2)
 >>> key,value = pairs[0]
 >>> key,value
('wicky', 'hip')
 >>> d={}
 >>> d[key]=value
 >>> d
{'wicky': 'hip'}
 >>> d={}
 >>> for key,value in pairs:
    d[key]=value

   
 >>> d
{'woo': 'hoo', 'wacky': 'hop', 'wicky': 'hip'}


Or shortly:

 >>> d={}
 >>> for key,value in zip(l1,l2):
    d[key]=value

   
 >>> d
{'woo': 'hoo', 'wacky': 'hop', 'wicky': 'hip'}
 >>>

hth, gl