Looking up a dictionary _key_ by key?

Dan Stromberg drsalists at gmail.com
Tue Jun 23 20:47:58 EDT 2015


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-2.4/bin/python good [1, 2, 3]
/usr/local/cpython-2.5/bin/python good [1, 2, 3]
/usr/local/cpython-2.6/bin/python good [1, 2, 3]
/usr/local/cpython-2.7/bin/python good [1, 2, 3]
/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/jython-2.7rc1/bin/jython good [3, 2, 1]
/usr/local/pypy-2.5.0/bin/pypy good [1, 2, 3]
/usr/local/pypy3-2.4.0/bin/pypy3 good dict_keys([1, 2, 3])

But:

$ ./pythons --command 'd={1:2, 2:4, 3:8}; print(d.keys()[1])'
/usr/local/cpython-2.4/bin/python good 2
/usr/local/cpython-2.5/bin/python good 2
/usr/local/cpython-2.6/bin/python good 2
/usr/local/cpython-2.7/bin/python good 2
/usr/local/cpython-3.0/bin/python bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
/usr/local/cpython-3.1/bin/python bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
/usr/local/cpython-3.2/bin/python bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
/usr/local/cpython-3.3/bin/python bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
/usr/local/cpython-3.4/bin/python bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
/usr/local/cpython-3.5/bin/python bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object does not support indexing
/usr/local/jython-2.7rc1/bin/jython good 2
/usr/local/pypy-2.5.0/bin/pypy good 2
/usr/local/pypy3-2.4.0/bin/pypy3 bad
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    TypeError: 'dict_keys' object is not subscriptable

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

Thanks!



More information about the Python-list mailing list