[Tutor] create dict from 2 lists

Lloyd Kvam pythonTutor at venix.com
Fri Apr 2 15:29:34 EST 2004


You can take that one step further.
p = dict(zip(keys,values))

dict will construct a dictionary from a list of pairs.

On Fri, 2004-04-02 at 08:38, Gregor Lingl wrote:
> BRINER Cedric schrieb:
> 
> > hi,
> >
> > assume that I want to create the dict:
> > p={1:11,2:22,3:33,4:44}
> >
> > and that i have:
> > the keys=[1,2,3,4]       and
> > the values=[11,22,33,44]
> >
> > Is the simpliest way to do this, is to do :
> > p={}
> > for i in range(len(keys)):
> >   p[keys[i]]=values[i]
> >
> > or is there a hidded function which do this?
> >
> You could use the non-hidden function zip:
> (See: Python Library Reference 2.1)
> 
>  >>> keys=[1,2,3,4]
>  >>> values=[11,22,33,44]
>  >>> p={}
>  >>> for key,value in zip(keys,values):
>     p[key]=value
>   
>  >>> p
> {1: 11, 2: 22, 3: 33, 4: 44}
> 
> Regards, Gregor
> 
> 
> > Cédric BRINER
> >
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list