loop over list and process into groups

mk mrkafk at gmail.com
Thu Mar 4 11:55:10 EST 2010


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




More information about the Python-list mailing list