473,394 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Dictionary that uses regular expressions

Hello all,

I wrote the code below. It is simply a dictionary that uses regular
expressions to match keys. A quick look at _test() will give you an
example.

Is there a module that already does this? Is there a way and would it
be better to use list comprehension? (using python 2.3)

Just looking for a better or more pythonic way to do it.

import re

class ReDict(dict):
'''
A dictionary that uses regular expressions keys

NOTE:
if the redict finds more than one key that matches the re it
returns a redict of all of the matching keys
'''
def __init__(self):
dict.__init__(self)
self.re=1

def reOn(self):
'''
turn regular expression matching on
'''
self.re=1

def reOff(self):
'''
turn regular expression matching off
'''
self.re=0

def __getitem__(self,key):
if self.re ==1:
temp = ReDict()
for item in self.items():
if re.search(key,item[0]): #line match
temp[item[0]]=item[1]

if len(temp)==1:
return temp.values()[0]

return temp
else:
return dict.__getitem__(self,key)
def _test():
d=ReDict()

d["price"]=7.25
d['call jan 5.0']=1
d['call jan 7.5']=1.5
d['put jan 7.5']=7.2

d['call feb 5.0']=2
d['call feb 7.5']=2.5
d['put feb 7.5']=6.8

d['call mar 5.0']=3
d['call mar 7.5']=3.5
d['put mar 7.5']=4

d['call apr 5.0']=4
d['call apr 7.5']=4.5
d['put apr 7.5']=6.2

d['call may 5.0']=5
d['call may 7.5']=5.5
d['put may 7.5']=4.9

print d['price'] #prints the price
print d['call']['may']['7.5'] # prints individual value
print d['call'] #returns a redict of all calls
print d['put'] #returns a redict of all puts
print d['may'] #returns a redict of all options in may

_test()
Thanks,
Erik Lechak
Jul 18 '05 #1
3 7272

"Erik Lechak" <pr*****@netzero.net> wrote in message
news:1f**************************@posting.google.c om...
Hello all,

I wrote the code below. It is simply a dictionary that uses regular
expressions to match keys. A quick look at _test() will give you an
example.

Is there a module that already does this?
Not that I know of
Is there a way and would it
be better to use list comprehension? (using python 2.3)


List comp builds a list. Your __getitem__(s,key) code builds an
ReDict, not a list. If you extended your initializer to initialize
from a list of items (by passing the list of items on to
dict.__init__), then you could build such a list with a l.c. and
initialize your return ReDict from that. IE (untested, obviously, and
it's late...)

return ReDict( [item for item in self.items if
re.search(key,item[0]) ] )

If you were always (or even almost always) matching by re's, you might
as well just use a list of items (key,value). If you really must mix
normal and re retrieval, but only after the dict is built and stable,
then keeping items() as an attribute rather than re-extracting it for
each re access would be faster.

Terry J. Reedy
Jul 18 '05 #2
I would leave the __getitem__() method alone and just add a
filterMatches(self, regexp) returning a ReDict or findMatches(self, regexp)
returning a list/iterator of values. That preserves the symmetry of

theDict[key] = value
value = theDict[key]

element access. It also makes client code more explicit as you can clearly
distinguish the reOn

x = theDict.filterMatches(bla)

and reOff

x = theDict[bla]

cases. Both reOn() and reOf() are no longer needed, plus you need not
overwrite __init__(), which preserves its expected (by users of dict)
behaviour.

Peter
Jul 18 '05 #3
On Thu, Aug 21, 2003 at 05:05:52AM +0000, Raymond Hettinger wrote:
"Erik Lechak" <pr*****@netzero.net> wrote in message
news:1f**************************@posting.google.c om...
Hello all,

I wrote the code below. It is simply a dictionary that uses regular
expressions to match keys. A quick look at _test() will give you an
example.

Is there a module that already does this?


Google may prove me wrong, but this looks like a new idea.

Is there a way and would it
be better to use list comprehension? (using python 2.3)

Just looking for a better or more pythonic way to do it.


Try inheriting from UserDict.DictMixin instead of dict.


Some months ago I started rewriting the C regexps module to allow for
matching pure-python string types[1]. The python class would just have
to define a method to get the next character and optionally a method
to say how much to backtrack on a match failure. My use case was ternary
trees, instead of doing a lookup with a string key it would return
first or any matches of a regexp key.

Other people were doing heavy work on the regexp module so I'm waiting
for the 2.4 implementation to stabalize before I go back to it.

-jackdied

[1] http://mail.python.org/pipermail/pyt...il/034688.html
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Dan | last post by:
Hello, I'd like to be able to take a formatted string and determine the replacement dictionary necessary to do string interpolation with it. For example: >>> str = 'his name was %(name)s and...
8
by: Rodd Snook | last post by:
I have an application which makes extensive use of the Scripting.Dictionary object. I'm not doing anything silly like putting them outside the page scope -- just creating quite a few of them and...
2
by: Sehboo | last post by:
Hi, I have several regular expressions that I need to run against documents. Is it possible to combine several expressions in one expression in Regex object. So that it is faster, or will I...
4
by: Együd Csaba | last post by:
Hi All, I'd like to "compress" the following two filter expressions into one - assuming that it makes sense regarding query execution performance. .... where (adate LIKE "2004.01.10 __:30" or...
3
by: a | last post by:
I'm a newbie needing to use some Regular Expressions in PHP. Can I safely use the results of my tests using 'The Regex Coach' (http://www.weitz.de/regex-coach/index.html) Are the Regular...
25
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART...
1
by: Allan Ebdrup | last post by:
I have a dynamic list of regular expressions, the expressions don't change very often but they can change. And I have a single string that I want to match the regular expressions against and find...
13
by: Wiseman | last post by:
I'm kind of disappointed with the re regular expressions module. In particular, the lack of support for recursion ( (?R) or (?n) ) is a major drawback to me. There are so many great things that can...
12
by: FAQEditor | last post by:
Anybody have any URL's to tutorials and/or references for Regular Expressions? The four I have so far are: http://docs.sun.com/source/816-6408-10/regexp.htm...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.