[Tutor] making list into a dictionary
McLaughlin, Toby
tmclaughlin at csu.edu.au
Fri Nov 5 05:50:29 CET 2004
Even
c = dict(zip(a,b))
will work because of the overloaded constructor on "dict".
>From help(dict)
class dict(object)
| dict() -> new empty dictionary.
<snip>
| dict(seq) -> new dictionary initialized as if via:
| d = {}
| for k, v in seq:
| d[k] = v
Toby McLaughlin.
> -----Original Message-----
> From: tutor-bounces at python.org
> [mailto:tutor-bounces at python.org] On Behalf Of Bill Mill
> Sent: Friday, 5 November 2004 3:44 PM
> To: kumar s
> Cc: tutor at python.org
> Subject: Re: [Tutor] making list into a dictionary
>
>
> 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
> >
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list