[Python-ideas] Add dict.getkey() and set.get()

MRAB python at mrabarnett.plus.com
Sat Sep 14 19:27:00 CEST 2013


On 14/09/2013 16:09, Serhiy Storchaka wrote:
> I propose to add two methods:
>
> dict.getkey(key) returns original key stored in the dict which is equal
> to specified key. E.g.
>
>   >>> d = {2: 'a', 5.0: 'b'}
>   >>> d.getkey(2.0)
> 2
>   >>> d.getkey(5)
> 5.0
>   >>> d.getkey(17)
> Traceback (most recent call last):
>     File "<stdin>", line 1, in <module>
> KeyError: 17
>
> set.get(value) returns original value stored in the set which is equal
> to specified value. E.g.
>
>   >>> s = {2, 5.0}
>   >>> s.get(2.0)
> 2
>   >>> s.get(5)
> 5.0
>   >>> s.get(17)
> Traceback (most recent call last):
>     File "<stdin>", line 1, in <module>
> KeyError: 17
>
There's discussion on python-dev about adding TransformDict with a
.getitem method. Adding a .getkey method to dicts would not be
consistent with that; really they should either both have .getitem or
both have .getkey.


More information about the Python-ideas mailing list