Looking up a dictionary _key_ by key?

Ben Finney ben+python at benfinney.id.au
Tue Jun 23 21:07:46 EDT 2015


Dan Stromberg <drsalists at gmail.com> writes:

> On Tue, Jun 23, 2015 at 5:33 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> > Dan Stromberg <drsalists at gmail.com> writes:
> >
> >> 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?
> >
> > The dictionary knows its keys and can provide them on request. Call the
> > ‘dict.keys’ method to get them as a collection.
>
> So it appears:
>
> $ ./pythons --command 'd={1:2, 2:4, 3:8}; print(d.keys())'
[…]
> /usr/local/cpython-3.0/bin/python good <dict_keys object at 0x8514fa4>
> /usr/local/cpython-3.1/bin/python good dict_keys([1, 2, 3])
> /usr/local/cpython-3.2/bin/python good dict_keys([1, 2, 3])
> /usr/local/cpython-3.3/bin/python good dict_keys([1, 2, 3])
> /usr/local/cpython-3.4/bin/python good dict_keys([1, 2, 3])
> /usr/local/cpython-3.5/bin/python good dict_keys([1, 2, 3])
> /usr/local/pypy3-2.4.0/bin/pypy3 good dict_keys([1, 2, 3])

Note that none of these (from Python 3) are lists; I don't promise a
list, only a collection :-)

> Would I have to do an O(n) search to find my key?

If you're wanting to *locate* a particular item, you'll need to find it
using whatever comparisons the values support. You described some custom
type; the answer will depend on what that type supports for comparing
values.

What I can say at this point is: we are no longer talking about anything
special to dictionary keys. You just have a collection of values, which
you can iterate over and compare to some target.

-- 
 \           “The long-term solution to mountains of waste is not more |
  `\      landfill sites but fewer shopping centres.” —Clive Hamilton, |
_o__)                                                _Affluenza_, 2005 |
Ben Finney




More information about the Python-list mailing list