problem of converting a list to dict

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Jan 9 20:08:15 CET 2008


On Wed, 09 Jan 2008 10:56:36 -0800, Louis.Soninhu wrote:

> Hi pals
> 
> I have a list like this
> 
> mylist=['','tom=boss','mike=manager','paul=employee','meaningless']
> 
> I'd like to remove the first and the last item as they are irrevalent,
> and convert it to the dict:
> {'tom':'boss','mike':'manager','paul':'employee'}
> 
> I tried this but it didn't work:
> 
> mydict={}
> for i in mylist[1:-1]:
> 	a=i.split('=')		# this will disect each item of mylist into a 2-item
> list
> 	mydict[a[0]]=a[1]
> 
> and I got this:
>   File "srch", line 19, in <module>
>     grab("a/tags1")
>   File "srch", line 15, in grab
>     mydict[mylist[0]]=mylist[1]
> IndexError: list index out of range
> 
> Anyone could shed me a light on this?

The real list you used had at least one string without a '=' in it.  The
list given above doesn't raise that exception:

In [102]: mylist=['','tom=boss','mike=manager','paul=employee','meaningless']

In [103]: mydict={}

In [104]: for i in mylist[1:-1]:
   .....:     a=i.split('=')
   .....:     mydict[a[0]]=a[1]
   .....:

In [105]: mydict
Out[105]: {'mike': 'manager', 'paul': 'employee', 'tom': 'boss'}

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list