Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #93064

Re: Looking up a dictionary _key_ by key?

From Peter Otten <__peter__@web.de>
Subject Re: Looking up a dictionary _key_ by key?
Date 2015-06-24 08:44 +0200
Organization None
References <CAGGBd_pd9SA7SczanGARFr-+Z9SxP9Mkhfo-RivpcJLrnuexng@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.6.1435128250.3674.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Looking up a dictionary _key_ by key? Peter Otten <__peter__@web.de> - 2015-06-24 08:44 +0200

csiph-web