Lists and Tuples and Much More

Hendrik van Rooyen mail at microcorp.co.za
Sun Apr 15 05:07:31 EDT 2007


 "James Stroud" <jstroud at mbi.ucla.edu> wrote:

> Hendrik van Rooyen wrote:

> >
> > But if you limit it to one thing and its inverse, its quite useful, and it
> > would be nice to have one "doubledict" that can be accessed as speedily
> > from either end...
> >
> > Sort of an internally linked list of mixed hashed immutables, where:
> >
> > doubledict["Frank Everyman"] yields addy, and
> > doubledict[addy] yields "Frank Everyman"
> >
> > It would have direct applicability in things like the label table in
> > an assembler, for debugging and so on.
> >
> > - Hendrik
> >
>
> I'm thinking that, to avoid big a lot of ambiguity, such a double dict
> would need to be implemented as two distinctly referenced data structures:

not sure that I agree with this - what I have in mind is almost like this:

{a:b,b:a,.....} - but avoiding the overhead of storing the "keys" and "data"
twice...

Guess at notation:

{<a:b>,<c:d>,....}  - I know the <> is ugly so lets try:

{(a:b),(c:d),...}    - not much better...


>
> class DD(object):
>    def __init__(self, adict):
>      self._fwd = {}
>      self._fwd.update(adict)
>      self._bkwk = dict(v,k for k,v in adict.items())
>    def fwd(self, k)
>      return self._fwd[k]
>    def bkwd(self, k)
>      return self._bkwd[k]
>    def __setitem__(self, k, v):
>      self._fwd[k] = v
>      self._bkwd[v] = k
>    def __getitem__(self, k):
>      if (k in self._fwd) and (k in self._bkwd):
>        raise KeyError, 'Which do I look in first?'
>      else:
>        raise KeyError, 'Too much guesswork. Use fwd() or bkwd().'
>
> James

This is the problem - you can also do it with two dicts, but then you have to
do try-except and handle KeyError if you guess wrong. This is what I have
been doing.

I think that trying to go "back and forth" is a mistake - easier to just have
one
link, and store "thing" and "pointer to thing's partner".

In practice you would probably either "know" what you are dealing with
because of where you got the thing you are looking up from, or in true
duck typing style you would not "care".

On the other hand, if you store two links, then you can have:

"thing", "pointer to next thing in group", "pointer to previous thing in group"

and then you can have something like:

dd={(a:b:c),(d:e:f:g:h),....}

and that would return a list [a,b,c], from any of dd[a], dd[b], dd][c],
and likewise for "entry points" of d,e,f,g, or h, to yield [d,e,f,g,h]

This makes me think that the correct notation would be:

{[a,b,c],[d,e,f,g,h],...}

but maybe not because it looks like a set of lists...

then how about:

{[a:b:c],[d:e:f:g:h],...}

and yes I know that:

{[a:b:c:f],[d:e:f:g:h],...} - can't be done using
only two pointers,  not even with fancy footwork

- Hendrik





More information about the Python-list mailing list