a clean way to define dictionary
Michele Simionato
mis6 at pitt.edu
Wed Jun 18 12:51:02 EDT 2003
Kendear <kendear at nospam.com> wrote in message news:<3EEFEBFD.8090003 at nospam.com>...
> 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?
lst = """\
a 1
foo 3
bar 234
joe 321
"""
d=dict([(line.split()[0],int(line.split()[1])) for line in lst.splitlines()])
print d
#=>{'a': 1, 'foo': 3, 'bar': 234, 'joe': 321}
More information about the Python-list
mailing list