Looking up a dictionary _key_ by key?

Peter Otten __peter__ at web.de
Wed Jun 24 02:44:00 EDT 2015


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?

$ cat grab_key.py
class GrabKey:
    def __init__(self, key):
        self.key = key

    def __eq__(self, other):
        if self.key == other:
            self.dict_key = other
            return True
        return False

    def __hash__(self):
        return hash(self.key)


def grab_key(k, d):
    g = GrabKey(k)
    d[g]
    return g.dict_key


if __name__ == "__main__":
    d = {1: int, 2.0: float}
    print(grab_key(1.0, d))
    print(grab_key(2, d))
$ python3 grab_key.py 
1
2.0





More information about the Python-list mailing list