Looking up a dictionary _key_ by key?

Steven D'Aprano steve at pearwood.info
Tue Jun 23 21:49:25 EDT 2015


On Wed, 24 Jun 2015 10:21 am, Dan Stromberg wrote:

> I know that sounds strange: usually we look up values by key, not keys.
> 
> But suppose you have a strange key type that despite being "equal", is
> not identical in some fields, and you need to see those fields.
> 
> Is there a way of getting the key used by the dictionary, short of
> storing a reference to it in the value, or using a second dictionary?

A nice problem from an ugly situation. The short answer is, no.

Python's dictionary lookup algorithm could be something like this:

- take the hash of the key, h;
- inspect slot h of the internal array;
- if it contains a key equal to the input key, return the value
- otherwise deal with a collision somehow


You're basically asking for step 3 to return the input key instead of the
value. Short of re-writing the dict type, no, there is no way to do so.

Without knowing your application, I can't really know what the right
approach is. One might be to ensure that only a canonical version of the
key is used in the first place, by interning it.


ALIVE = {}
def intern(key):
    return ALIVE.setdefault(key, key)


If you pass two objects that are equal but not identical, the first one will
become the canonical interned value, and the second time you will get the
first one back.

If interning doesn't suit, you can do a linear search through the keys to
find the one which matches:

for k in mydict:
    if k == key:
        assert mydict[k] is mydict[key]
        print(k, "equals but is not identical to", key)


-- 
Steven




More information about the Python-list mailing list