[Python-ideas] Add dict.getkey() and set.get()
Oscar Benjamin
oscar.j.benjamin at gmail.com
Sun Sep 15 22:02:33 CEST 2013
On 15 September 2013 00:07, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Sep 14, 2013 at 09:52:30AM -0700, David Mertz wrote:
>
>> def getexact(m, v):
>> for x in m:
>> if x==v: return x
>> else:
>> raise KeyError(v)
>
> This has the flaw that it is O(N) rather than O(1). It's really quite
> unfortunate to have dicts and sets able to access keys in (almost)
> constant time, but not be able to communicate that key back to the
> caller except by walking the entire dict/set.
I don't know whether this is relying on undefined behaviour but the
following is O(1) and seems to work:
>>> def canonical_key(d, k):
... k, = {k} & d.keys()
... return k
...
>>> canonical_key({1:'q', 2.0:'w'}, 1.0)
1
>>> canonical_key({1:'q', 2.0:'w'}, 2)
2.0
Oscar
More information about the Python-ideas
mailing list