Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #93064 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2015-06-24 08:44 +0200 |
| Last post | 2015-06-24 08:44 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Looking up a dictionary _key_ by key? Peter Otten <__peter__@web.de> - 2015-06-24 08:44 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2015-06-24 08:44 +0200 |
| Subject | Re: Looking up a dictionary _key_ by key? |
| Message-ID | <mailman.6.1435128250.3674.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web