如何在python中获取字典中键的位置

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

How to get position of key in a dictionary in python

pythondictionaryordereddictionary

提问by gweno10

If a key is present in a dictionary, I want to know what position the key is in i.e the numerical index. For example :

如果字典中存在键,我想知道键在哪个位置,即数字索引。例如 :

if the dictionary consists of :

如果字典包含:

{'test':{1,3},'test2':{2},'test3':{2,3}}

if 'test' in dictionary:
   print(the index of that key)

The output would be 0 for example. (The output would be 2 for 'test3'...)

例如,输出将为 0。('test3' 的输出将为 2...)

I'm using a dictionary at the moment, I'm guessing I'd have to use an ordered dictto do this, but how can I do it using an ordered dict?

我目前正在使用字典,我猜我必须使用 orderdict来做到这一点,但是我怎么能用一个 orders来做到这一点dict

Thanks for any help.

谢谢你的帮助。

回答by Aaron Christiansen

For Python <3.6, you cannot do this because dictionaries in Python have no order to them, so items don't have an index. You could use an OrderedDictfrom the collectionslibrary instead though, and pass it a tuple of tuples:

对于 Python <3.6,您不能这样做,因为 Python 中的字典对它们没有顺序,因此项目没有索引。你可以使用一个OrderedDictcollections图书馆,虽然,而是和它传递的元组的元组:

>>> import collections
>>> d = collections.OrderedDict((('test',{1,3}),('test2',{2}),('test3',{2,3})))
>>> d.keys().index('test3') # Replace with list(d.keys()).index("test3") for Python 3
2

回答by Steven C. Howell

As of Python 3.6, dictionaries now preserves the insertion order. So using Python 3.6+, you could get the index by converting the dict_keysto a list.

从 Python 3.6 开始,字典现在保留了插入顺序。因此,使用 Python 3.6+,您可以通过将 转换dict_keys为列表来获取索引。

dictionary = {'test':{1,3}, 'test2':{2}, 'test3':{2,3}}

if 'test' in dictionary:
   print(list(dictionary).index('test'))

As another example, the following demonstrates how to find the index for a few keys of interest.

作为另一个例子,下面演示了如何找到几个感兴趣的键的索引。

key_list = list(dictionary)
keys_of_interest = ['test2', 'test3']

for key in keys_of_interest:
    print('key: {}, index: {}'.format(key, key_list.index(key)))

The output from this would be

输出将是

key: test2, index: 1
key: test3, index: 2

回答by B. M.

You can just build an index :

你可以只建立一个索引:

ind= {k:i for i,k in enumerate(dictionary.keys())}

then ind['test3']will be 2, with O(1) access time.

然后ind['test3']将是 2,访问时间为 O(1)。

This is robust while keys are fixed. If you add/remove keys, you have to rebuild the index.

这是健壮的,而键是固定的。如果添加/删除键,则必须重建索引。

回答by wnnmaw

Unfortunately, such a thing is not possible because of how dictionaries are constructed in python. These data structures are inherently unordered.

不幸的是,由于python中字典的构造方式,这种事情是不可能的。这些数据结构本质上是无序的

To get the functionallity you want you must use a different data structure, such as OrderedDict

要获得您想要的功能,您必须使用不同的数据结构,例如OrderedDict

回答by Richard

With python 3.6 or later, with dicts preserving insertion order, then you can do it in one line, with it returning 'None' if the key isn't in the dictionary:

使用 python 3.6 或更高版本,使用 dicts 保留插入顺序,那么您可以在一行中完成,如果键不在字典中,则返回“None”:

key_index = list(my_dictionary).index(the_key) if the_key in my_dictionary else None

回答by Biarys

You can just convert dict.keys() to a list and then index the list

您可以将 dict.keys() 转换为列表,然后索引列表

keys = list(dictionary.keys()
index = keys.index("test")

indexing values that are not in the list will result in ValueError

索引不在列表中的值将导致 ValueError

keys.index("test5")
ValueError: "test5" is not in list