a clean way to define dictionary

Bryan belred1 at yahoo.com
Wed Jun 18 01:06:37 EDT 2003


"Kendear" <kendear at nospam.com> wrote in message
news:3EEFEF90.4000703 at nospam.com...
> Kendear wrote:
> >
> > i hope to define a dictionary this way:
> >
> > lst = """
> > a    1
> > foo  3
> > bar  234
> > joe  321
> > """
> >
> > lst = lst.split()
> >
> > now lst refers to  ['a', '1', 'foo', '3', 'bar', '234', 'joe', '321']
> > i want to do something like
> >
> > dict = {}
> > for key, value in lst:
> >     dict[key] = eval(value)
> >
> >
> > but key, value is not for taking 2
> > items at a time, but take a tuple
> > and unpacking it...
> >
> > is there a way for the "for"
> > to take 2 items at a time?
> >
> > or is there a more common way to define a dictionary
> > without all the punctuation marks?
>
>
> of course, it can be done as
>
> for i in range(0, len(lst), 2):
>      dict[lst[i]] = eval(lst[i+1])
>
> but is a little messy... is there a cleaner way?
>

how about this?
dict(zip(lst[0::2], map(eval, lst[1::2])))

also, i don't think it's a good idea to use dict as a variable name since
dict is a python type.

bryan







More information about the Python-list mailing list