[Tutor] how to convert list of lists to dict

Alan Gauld alan.gauld at btinternet.com
Tue May 17 22:51:37 CEST 2011


"Brad Hudson" <brad.hudson at gmail.com> wrote

> > Given that you want more than one method I assume
> > this is a homwework assignment
> It's really more that I'm a newbie to python. Trying to translate 
> from perl
> to python in my head...

OK, Thats fine, it just seemed odd that you asked for 3
solutions to the problem rather than one!

> This is where I started (not elegant at all, but learning):

> def get_vms():
>         import subprocess

Its best (and conventional) to do imports at the top of
your modules outside function definition.

>         p = subprocess.Popen(['/usr/sbin/ldm', 'ls', '-p'],
> stdout=subprocess.PIPE).communicate()[0]
>         p = p.split('\n')

A more meaningful name than p might be helpful! :-)

>        [p.remove(item) for item in p if not 
> item.startswith('DOMAIN')]

List comprehensions are intended for building lists.
Don't use them as a loop to generate side-effects.
This would be better with the explicit:

for item in p:
    if not item.startswith('DOMAIN'):
         p.remove(item)

>         p = [item.replace('DOMAIN|', '') for item in p]
>         p = [i.split('|') for i in p]

And while these are valid comprehensions you are
looping over the same list many times so its probably
better to fully process each line as yyou go using an
explicit loop, So it becomes:

items = []
for item in p:
    if not item.startswith('DOMAIN'):
       p.remove(item)
    else:
        items.append(item.replace('DOMAIN|', '').split('|'))
    print items

That should leave you with a list of lists.
You can now iterate over items to extract your
dictionary keys and create the dictionary values
associated with it.

Or, instead of appending you could do the dictionary addition
in the loop. But I'd suggest doing it via a second helper
function that takes an item list and returns a dictionary.
So it looks like:

         else:
              item = item.replace('DOMAIN|', '').split('|')
              mydict[item[n]] = buildItemDict(item)

where n is whatever index yields your key...
and buidItemDict is your helper function.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list