creating a dictionary from a dictionary with regex

J

james_027

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
 
M

Marc 'BlackJack' Rintsch

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top