On Wed, Jan 14, 2009 at 4:30 PM, Aaron Brady <[email protected]> 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. > > For a reverse lookup, you just need two lookups. > name= {} > phone= {} > name[ '555-963' ]= 'Joan' > phone[ 'Joan' ]= '555-963' > > Though maybe the keys in 'name' should be names, instead of the values > in it. The variable name doesn't clarify that. (What is more natural > to you in reading code? Is one obviously wrong?) > > phone[ '555-963' ]= 'Joan' > name[ 'Joan' ]= '555-963' > > To provide for non-unique fields, the structure becomes kind of > complicated. > > phone[ '555-963' ]= 'Joan' > phone[ '555-964' ]= 'Joan' > name[ 'Joan' ]= [ '555-963', '555-964' ] > > For uniform access, 'phone' can be a dict of strings to lists too. > > phone[ '555-963' ]= [ 'Joan' ] > phone[ '555-964' ]= [ 'Joan' ] > > To add a third field, the structure becomes again more complicated. > Either define a unique key: > > phone[ '555-963' ]= [ object1 ] > phone[ '555-964' ]= [ object2 ] > name[ 'Joan' ]= [ object1, object2 ] > hourstocall= {} > hourstocall[ '9a-5p' ]= [ object1 ] > hourstocall[ '5p-11p' ]= [ object2 ] > records= {} > records[ object1 ]= ( 'Joan', '555-963', '9a-5p' ) > records[ object2 ]= ( 'Joan', '555-964', '5p-11p' ) > > 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). Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
