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


Groups > comp.lang.python > #93058

Re: Looking up a dictionary _key_ by key?

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: Looking up a dictionary _key_ by key?
Date 2015-06-24 11:07 +1000
References <CAGGBd_pd9SA7SczanGARFr-+Z9SxP9Mkhfo-RivpcJLrnuexng@mail.gmail.com> <851th2t05t.fsf@benfinney.id.au> <CAGGBd_qaNC38Yg0u_b8+qBAckq6FRTZMxbWwuzV=MUYE_=ZzDw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.4.1435108074.3674.python-list@python.org> (permalink)

Show all headers | View raw


Dan Stromberg <drsalists@gmail.com> writes:

> On Tue, Jun 23, 2015 at 5:33 PM, Ben Finney <ben+python@benfinney.id.au> wrote:
> > Dan Stromberg <drsalists@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

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


Thread

Re: Looking up a dictionary _key_ by key? Ben Finney <ben+python@benfinney.id.au> - 2015-06-24 11:07 +1000

csiph-web