Can dictionary values access their keys?

Jeremy Bowers jerf at jerf.org
Fri Apr 8 16:34:35 EDT 2005


On Fri, 08 Apr 2005 10:33:53 -0600, Matthew Thorley wrote:
> I must say I am *very* suprised that python does not have a way to look
> up what key is pointing to a given object--without scanning the whole
> list that is.

Assuming fairly optimal data structures, nothing is free.

Python chooses not to have bi-directional dicts built in. A good reason
for this is that it is easy to build a two-way dict out of two one-way
dicts, and there's no obvious way to build a "built-in" two-way dict that
is any more efficient than that.

Python chooses to allow all objects potentially to be dict keys, which has
overhead vs. an implementation such as that in Perl that only allows
strings. Either of those is tolerable ultimately, though I do prefer
Python's approach as I key things on objects all the time.

It's all a matter of tradeoffs. Building all the dicts as two-way in
memory consumes twice the memory and twice the processor power for a lot
of situations where the second direction isn't used, so *on average*
that's not a good tradeoff. 

Even though Python doesn't have a built-in way, it is easy to write your
own class that interoperates transparently, and there are many ones you
can grab off the 'net, even given to you in this thread :-)




More information about the Python-list mailing list