problem of converting a list to dict

John Machin sjmachin at lexicon.net
Wed Jan 9 14:45:43 EST 2008


On Jan 10, 5:56 am, Louis.Soni... at gmail.com 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

No it doesn't; it dissects i into a 2-item list if i is a string
containing exactly one '='.

DON'T rely on "knowing" that the first and last entries are the only
irrelevant ones. Do some checking. Conditions to check for:
(1) len(a) == 2
(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', ...]





More information about the Python-list mailing list