Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > creating a dictionary from a dictionary with regex

Reply
Thread Tools

creating a dictionary from a dictionary with regex

 
 
james_027
Guest
Posts: n/a
 
      08-22-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

 
Reply With Quote
 
 
 
 
Marc 'BlackJack' Rintsch
Guest
Posts: n/a
 
      08-22-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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Performance ordered dictionary vs normal dictionary Navkirat Singh Python 6 07-29-2010 10:18 AM
Re: Performance ordered dictionary vs normal dictionary Chris Rebert Python 0 07-29-2010 06:11 AM
How make regex that means "contains regex#1 but NOT regex#2" ?? seberino@spawar.navy.mil Python 3 07-01-2008 03:06 PM
[DICTIONARY] - Copy dictionary entries to attributes Ilias Lazaridis Python 6 02-21-2006 11:27 AM
dictionary within dictionary Fox ASP General 5 03-13-2005 05:03 AM



Advertisments