Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   creating a dictionary from a dictionary with regex (http://www.velocityreviews.com/forums/t531639-creating-a-dictionary-from-a-dictionary-with-regex.html)

james_027 08-22-2007 07:13 AM

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


Marc 'BlackJack' Rintsch 08-22-2007 07:39 AM

Re: creating a dictionary from a dictionary with regex
 
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


All times are GMT. The time now is 01:13 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.