[Tutor] making list into a dictionary

Bill Mill bill.mill at gmail.com
Fri Nov 5 05:44:29 CET 2004


Kumar,

Here's what I'd do:

a = [1,2,3]
b = ['a','b','c']
d = {}

for key, val in zip(a, b):
    d[key] = val

The trick here is in the zip() function. This combines two lists like
a zipper - first element of the first list followed by first element
of the second list, then the second element of the first, and so on.
An example might help more:

>>> a = [1,2,3]
>>> b = ['a', 'b', 'c']
>>> zip(a,b)
[(1, 'a'), (2, 'b'), (3, 'c')]

The resulting list of tuples is easy to unpack, as we showed in the
earlier example.

Peace
Bill Mill
bill.mill at gmail.com


On Thu, 4 Nov 2004 20:18:45 -0800 (PST), kumar s <ps_python at yahoo.com> wrote:
> Dear group,
>  I want to convert 2 lists into a dictionary object.
> 
> Can I do that using list comprehension or by any other
> method:
> 
> a = ['apple', 'carrot', 'egg', 'cicken']
> b = ['fruit', 'vegie', 'poultry', 'meat']
> 
> c = {}
> 
> I want to create:
> c = {'fruit':'apple',
> 'vegie':'carrot',
> 'poultry':'egg',
> 'mean':'chicken'}
> 
> Could any one help, please.
> 
> Thanks
> Kumar.
> 
> __________________________________
> Do you Yahoo!?
> Check out the new Yahoo! Front Page.
> www.yahoo.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list