Can dictionary values access their keys?

Terry Reedy tjreedy at udel.edu
Fri Apr 8 16:54:51 EDT 2005


"Matthew Thorley" <ruach at chpc.utah.edu> wrote in message 
news:d36bpj$s59$1 at vegh.ks.cc.utah.edu...
> 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

But it does.  Of course, there could be zero to many keys in any dictionary 
pointing to any particular value object

>--without scanning the whole list that is.

That's one way.  Another is a reverse dict (for hashable values turned into 
keys) with the value being a list of zero to many keys.  A third (and 
fastest of these) is to keep the key with the value.

>Is that what list.index() does under-the-hood? I mean is
> list.index(y) just the same as
>
> itemnum = 0
> for item in list:
> if y == item:
> return itemnum
> else:
> itemnum = itemnum+1

More or less, yes.  If  your list is sorted, you can use binary search in 
the bisect module.

Terry J. Reedy






More information about the Python-list mailing list