pythonpython-3.xdictionarytypeerrorattributeerror

Accessing dict_keys element by index in Python3


I'm trying to access a dict_key's element by its index:

test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys()  # dict_keys object

keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'

I want to get foo.

same with:

keys[0]
TypeError: 'dict_keys' object does not support indexing

How can I do this?


Solution

  • Call list() on the dictionary instead:

    keys = list(test)
    

    In Python 3, the dict.keys() method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:

    >>> test = {'foo': 'bar', 'hello': 'world'}
    >>> list(test)
    ['foo', 'hello']
    >>> list(test)[0]
    'foo'