loop over list and process into groups

Sneaky Wombat joe.hrbek at gmail.com
Thu Mar 4 12:41:45 EST 2010


On Mar 4, 10:55 am, mk <mrk... at gmail.com> wrote:
> Sneaky Wombat wrote:
> > I was going to write a def to loop through and look for certain pre-
> > compiled regexs, and then put them in a new dictionary and append to a
> > list,
>
> regexes are overkill in this case I think.
>
> > [ 'VLAN4065',
> >  'Interface',
> >  'Gi9/6',
> >  'Po2',
> >  'Po3',
> >  'Po306',
> >  'VLAN4068',
> >  'Interface',
> >  'Gi9/6',
> >  'VLAN4069',
> >  'Interface',
> >  'Gi9/6',]
>
> Why not construct an intermediate dictionary?
>
> elems = [ 'VLAN4065',
>   'Interface',
>   'Gi9/6',
>   'Po2',
>   'Po3',
>   'Po306',
>   'VLAN4068',
>   'Interface',
>   'Gi9/6',
>   'VLAN4069',
>   'Interface',
>   'Gi9/6',]
>
> def makeintermdict(elems):
>      vd = {}
>      vlan = None
>      for el in elems:
>          if el.startswith('VLAN'):
>              vlan = el.replace('VLAN','')
>          elif el == 'Interface':
>              vd[vlan] = []
>          else:
>              vd[vlan].append(el)
>      return vd
>
> def makelist(interm):
>      finlist = []
>      for k in interm.keys():
>          finlist.append({k:interm[k]})
>      return finlist
>
> if __name__ == "__main__":
>      intermediate = makeintermdict(elems)
>      print intermediate
>      finlist = makelist(intermediate)
>      print 'final', finlist
>
> {'4068': ['Gi9/6'], '4069': ['Gi9/6'], '4065': ['Gi9/6', 'Po2', 'Po3',
> 'Po306']}
> final [{'4068': ['Gi9/6']}, {'4069': ['Gi9/6']}, {'4065': ['Gi9/6',
> 'Po2', 'Po3', 'Po306']}]
>
> I hope this is not your homework. :-)
>
> Regards,
> mk

Thanks mk,

My approach was a lot more complex than yours, but your's is better.
I like itertools and was using islice to create tuples for (start,end)
string slicing.  Too much work though.  Thanks!

-j



More information about the Python-list mailing list