在python中按索引访问字典值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15114843/
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-18 13:22:51  来源:igfitidea点击:

Accessing dictionary value by index in python

pythondictionaryindexing

提问by Dmitry Dyachkov

I would like to get the value by key index from a Python dictionary. Is there a way to get it something like this?

我想通过 Python 字典中的键索引获取值。有没有办法得到这样的东西?

dic = {}
value_at_index = dic.ElementAt(index)

where indexis an integer

其中index是一个整数

采纳答案by NPE

Standard Python dictionaries are inherently unordered, so what you're asking to do doesn't really make sense.

标准 Python 词典本质上是无序的,因此您要求执行的操作实际上没有意义。

If you really, really know what you're doing, use

如果你真的,真的知道你在做什么,使用

value_at_index = dic.values()[index]

Bear in mind that adding or removing an element can potentially change the index of every other element.

请记住,添加或删除元素可能会更改每个其他元素的索引。

回答by MikeRand

If you really just want a random value from the available key range, use random.choiceon the dictionary's values (converted to list form, if Python 3).

如果您真的只想要可用键范围中的随机值,请使用random.choice字典的值(转换为列表形式,如果 Python 3)。

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

回答by user2426679

While you can do

虽然你可以做

value = d.values()[index]

It should be faster to do

这样做应该更快

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

编辑:我只是使用 len 100,000,000 的 dict 在最后检查索引来计时,第一个/values() 版本用了 169 秒,而第二个/next() 版本用了 32 秒。

Also, note that this assumes that your index is not negative

另外,请注意,这假设您的索引不是负数

回答by mohammed ali shaik

Let us take an example of dictionary:

让我们以字典为例:

numbers = {'first':0, 'second':1, 'third':3}

When I did

当我做

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

我收到一个错误:'dict_values' 对象不支持索引

When I did

当我做

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

迭代和提取值它也会给出一个错误:'dict' 对象没有属性 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

因此,我想出了通过索引访问字典元素的新方法,只需将它们转换为元组。

tuple(numbers.items())[key_index][value_index]

for example:

例如:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

如果您想编辑值或对值进行排序,则元组对象不允许项目分配。在这种情况下,您可以使用

list(list(numbers.items())[index])