Accessing dict_keys element by index in Python3

前端 未结 6 862
感情败类
感情败类 2020-11-27 15:52

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(         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 16:11

    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'
    

提交回复
热议问题