在 Python3 中按索引访问 dict_keys 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18552001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:02:51  来源:igfitidea点击:

Accessing dict_keys element by index in Python3

pythondictionarypython-3.xkey

提问by fj123x

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

我正在尝试通过索引访问 dict_key 的元素:

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.

我想得到foo

same with:

与:

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

How can I do this?

我怎样才能做到这一点?

采纳答案by Martijn Pieters

Call list()on the dictionary instead:

list()改为调用字典:

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:

在 Python 3 中,该dict.keys()方法返回一个字典视图对象,它作为一个集合。直接迭代字典也会产生键,因此将字典转换为列表会产生所有键的列表:

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

回答by Mark

Not a full answer but perhaps a useful hint. If it is really the first item you want*, then

不是一个完整的答案,但可能是一个有用的提示。如果它真的是你想要的第一个项目*,那么

next(iter(q))

is much faster than

list(q)[0]

for large dicts, since the whole thing doesn't have to be stored in memory.

对于大型字典,因为整个内容不必存储在内存中。

For 10.000.000 items I found it to be almost 40.000 times faster.

对于 10.000.000 件物品,我发现它快了近 40.000 倍。

*The first item in case of a dict being just a pseudo-random item before Python 3.6(after that it's ordered in the standard implementation, although it's not advised to rely on it).

* 在Python 3.6之前,dict 只是伪随机项的情况下的第一项(之后它在标准实现中排序,尽管不建议依赖它)。

回答by pranav dua

test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
    ls.append(key)
print(ls[0])

Conventional way of appending the keys to a statically defined list and then indexing it for same

将键附加到静态定义的列表然后为其建立索引的常规方法

回答by gerrit

In many cases, this may be an XY Problem. Why are you indexing your dictionary keys by position? Do you really need to? Until recently, dictionaries were not even ordered in Python, so accessing the first element was arbitrary.

在许多情况下,这可能是XY 问题。为什么要按位置索引字典键?你真的需要吗?直到最近,字典还没有在 Python 中排序,因此访问第一个元素是任意的。

I just translated some Python 2 code to Python 3:

我刚刚将一些 Python 2 代码翻译成 Python 3:

keys = d.keys()
for (i, res) in enumerate(some_list):
    k = keys[i]
    # ...

which is not pretty, but not very bad either. At first, I was about to replace it by the monstrous

这不是很漂亮,但也不是很糟糕。起初,我正准备用可怕的来代替它

    k = next(itertools.islice(iter(keys), i, None))

before I realised this is all much better written as

在我意识到这更好写之前

for (k, res) in zip(d.keys(), some_list):

which works just fine.

这工作得很好。

I believe that in many other cases, indexing dictionary keys by position can be avoided. Although dictionaries are ordered in Python 3.7, relying on that is not pretty. The code above only works because the contents of some_listhad been recently produced from the contents of d.

我相信在许多其他情况下,可以避免按位置索引字典键。尽管字典在 Python 3.7 中是有序的,但依赖它并不漂亮。上面的代码之所以有效,是因为 的内容some_list最近是从d.

Have a hard look at your code if you really need to access a disk_keyselement by index. Perhaps you don't need to.

如果您确实需要disk_keys按索引访问元素,请仔细查看您的代码。也许你不需要。

回答by Shirantha Madusanka

Try this

尝试这个

keys = [next(iter(x.keys())) for x in test]
print(list(keys))

The result looks like this. ['foo', 'hello']

结果看起来像这样。['foo', '你好']

You can find more possible solutions here.

您可以在此处找到更多可能的解决方案。

回答by Sheikh Abdul Wahid

I wanted "key" & "value" pair of a first dictionary item. I used the following code.

我想要第一个字典项的“键”和“值”对。我使用了以下代码。

 key, val = next(iter(my_dict.items()))