problem of converting a list to dict

Tim Chase python.list at tim.thechases.com
Wed Jan 9 15:12:24 EST 2008


> 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")


#2 and #3 can be ameliorated a bit by

   import string
   mydict = dict(
     map(string.strip,pair.split('=',1))
     for pair in mylist
     if '=' in pair)

which at least whacks whitespace off either end of your keys and 
values.  #4 and #5 require a clearer definition of the problem.

-tkc





More information about the Python-list mailing list