creating a dictionary from a dictionary with regex

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Aug 22 03:39:37 EDT 2007


On Wed, 22 Aug 2007 07:13:40 +0000, james_027 wrote:

> I am trying to create a dictionary from a dictionary which the help of
> regex to identify which keys to select. I have something like this but
> I feel its long and not the fastest solution ... could someone
> contribute?
> 
> import re
> 
> d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12, 'line2.item':'5c-BL
> Battery', 'line3.item':'N73', 'line5.item':'Screen Cover'}
> 
> collected = [k[:5] for k in d if re.match('^line\d+\.qty',k)]
> 
> for i in collected:
>     d2 = {}
>     for k in d:
>         if re.match('^%s\.\D+' % i, k):
>             d2[k] = d[k]
>     print d2

You are iterating over `d` for every item in `collected`.  With another
`dict` to store the results you can iterate over `d` only once:

from collections import defaultdict

def main():
    d= {'line2.qty':2, 'line3.qty':1, 'line5.qty':12,
        'line2.item':'5c-BL Battery', 'line3.item':'N73',
        'line5.item':'Screen Cover'}
    
    result = defaultdict(dict)
    for key, value in d.iteritems():
        new_key = key.split('.', 1)[0]  # Get the 'line#' part.
        result[new_key][key] = value
    print result

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list