On Jan 10, 7:12 am, Tim Chase <[EMAIL PROTECTED]> wrote: > > 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 > > This can be rewritten a little more safely like > > mydict = dict(pair.split('=',1) > for pair in mylist > if '=' in pair) > > Some of John Machin's caveats still apply: > (2) a[0] is empty or not what you expect (a person's name) > (3) a[1] is empty or not what you expect (a job title) > (consider what happens with 'tom = boss' ... a[0] = 'tom ', a[1] = ' > boss') > (4) duplicate keys [...., 'tom=boss', 'tom=clerk', ...] > > to which I'd add > > (5) what happens if you have more than one equals-sign in your > item? ("bob=robert=manager" or "bob=manager=big-cheese") >
or "bob==manager" ummm ... isn't more than one equals-sign covered by check #1: len(a) == 2 ? -- http://mail.python.org/mailman/listinfo/python-list