I hope you can help me with a problem I currently have. I need to build a dictionary with the following structure:
iplist={'32': [ '100.107.0.31/32', '100.107.0.3/32' ]
,'24': [ '100.107.0.0/24', '100.107.1.0/24', '100.107.2.0/24' ]
,'22': [ '100.107.0.0/22' ]
,'20': [ '100.107.0.0/20', '100.107.64.0/20' ]
,'16': [ '100.68.0.0/16', '100.69.0.0/16' ]
,'0' : [ '0.0.0.0' ] }
Input data will be this and I just need the keys:
netlabels={'100.107.0.31/32': 'aa'
,'100.107.0.3/32' : 'bb'
,'100.107.0.0/24' : 'cc'
,'100.107.1.0/24' : 'dd'
,'100.107.2.0/24' : 'ee'
,'100.107.0.0/22' : 'ff'
,'100.107.0.0/20' : 'gg'
,'100.107.64.0/20': 'hh'
,'100.68.0.0/16' : 'hh'
,'100.69.0.0/16' : 'hh'
,'0.0.0.0/0' : 'ii'}
I'm trying to do it with regular expression and list comprehension, because it would be really cool to have it all in one code line. My last 'successful' attempt was this:
>>> import re
>>> netlabels={'100.107.0.31/32' : 'aa'
... ,'100.107.0.3/32' : 'bb'
... ,'100.107.0.0/24' : 'cc'
... ,'100.107.1.0/24' : 'dd'
... ,'100.107.2.0/24' : 'ee'
... ,'100.107.0.0/22' : 'ff'
... ,'100.107.0.0/20' : 'gg'
... ,'100.107.64.0/20': 'hh'
... ,'100.68.0.0/16' : 'hh'
... ,'100.69.0.0/16' : 'hh'
... ,'0.0.0.0/0' : 'ii'}
>>>
>>> { re.sub(r'^[^/]+/(\d+)$', r'\1', k) : [k] for k in netlabels.keys() }
{'16': ['100.69.0.0/16'], '24': ['100.107.1.0/24'], '22': ['100.107.0.0/22'], '0': ['0.0.0.0/0'], '20': ['100.107.0.0/20'], '32': ['100.107.0.3/32']}
>>>
But obviously the the lists as values are too short. There were many prefixes just deleted or, to be more precisely, overwritten. What would be the way to push the values on a list and append this list each time a new value needs to be added?