creating a dictionary from a dictionary with regex

james_027 cai.haibin at gmail.com
Wed Aug 22 09:13:40 CEST 2007


Hi,

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

Thanks
james




More information about the Python-list mailing list