472,146 Members | 1,441 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,146 software developers and data experts.

creating a dictionary from a dictionary with regex

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

Aug 22 '07 #1
1 986
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
Aug 22 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Livin | last post: by
5 posts views Thread by Mark Rae | last post: by
2 posts views Thread by Matt | last post: by
6 posts views Thread by MikeSwann | last post: by
reply views Thread by Greg Corradini | last post: by
3 posts views Thread by JamesB | last post: by
1 post views Thread by Andrus | last post: by
reply views Thread by Saiars | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.