reverse dict lookup & Relation class
Aaron Brady
castironpi at gmail.com
Fri Jan 16 04:04:08 EST 2009
On Jan 14, 7:04 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Wed, Jan 14, 2009 at 4:30 PM, Aaron Brady <castiro... at gmail.com> wrote:
> > Hi, this is a continuation of something that comes up now and again
> > about reverse lookups on dictionaries, as well as a follow-up to my
> > pursuit of a Relation class from earlier.
snip
> > Or, and this is the interesting part, use the ('identificationally')
> > same tuples in both mappings, since the object is only mentioned, not
> > used.
>
> > phone[ '555-963' ]= [ ( 'Joan', '555-963', '9a-5p' ) ]
> > phone[ '555-964' ]= [ ( 'Joan', '555-964', '5p-11p' ) ]
> > name[ 'Joan' ]= [ ( 'Joan', '555-963', '9a-5p' ), ( 'Joan', '555-964',
> > '5p-11p' ) ]
> > hourstocall[ '9a-5p' ]= [ ( 'Joan', '555-963', '9a-5p' ) ]
> > hourstocall[ '5p-11p' ]= [ ( 'Joan', '555-964', '5p-11p' ) ]
>
> > What's the best way to construct this class? Or, do you have an
> > argument that it could not be simpler than using a relational db?
> > Brainstorming, not flamestorming.
>
> Once you get beyond a main dict (e.g. name2phone) and one that's its
> inverse (e.g. phone2name), yeah, I'd probably say you should be using
> a relational DB for this. You could also use objects, but it sounds
> like you really want to use SQL-like querying, which isn't well-suited
> to plain objects (though it'd be fine with an ORM).
I want the simplest data structure that can hold a relation. In this
case, I would declare a new record as:
PhoneInfo( 'Joan', '555-963', '9a-5p' )
PhoneInfo( 'Joan', '555-964', '5p-11p' )
However the syntax is flexible, such as in 'PhoneInfo.add' etc.
I can query the structure myself if I can access it as an iterable of
tuples. I think I want to use named tuples.
for rec in PhoneInfo.records:
if rec.name== 'Joan':
something
Or I can just use itertools.ifilter.
recset= ifilter( lambda rec: rec.name== 'Joan', PhoneInfo.records )
for rec in recset:
something
Using objects is one advantage, since they are "live" (unserialized)
and native, such as a relation of socket connections. (SQL would
require an additional mapping object and a key to accomplish it.)
More information about the Python-list
mailing list