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

问题描述 投票:8回答:5

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

如果字典包含:

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

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

例如,输出为0。 (对于“ test3”,输出为2。)

[我目前正在使用字典,我想我必须使用有序dict来执行此操作,但是如何使用有序dict来执行此操作?

感谢您的帮助。

python dictionary ordereddictionary
5个回答
9
投票
对于Python <3.6,您无法执行此操作,因为Python中的字典没有顺序,因此项目没有索引。您可以改用OrderedDict库中的collections,并将其传递给元组的元组:

>>> 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


4
投票
从Python 3.6开始,字典现在为preserves the insertion order。因此,使用Python 3.6+,您可以通过将dict_keys转换为列表来获取索引。

dictionary = {'test':{1,3}, 'test2':{2}, 'test3':{2,3}} if 'test' in dictionary: print(list(dictionary).index('test'))

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

key_list = list(dictionary) keys_of_interest = ['test2', 'test3'] for key in keys_of_interest: print('key: {}, index: {}'.format(key, key_list.index(key)))

此输出将是

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


2
投票
您可以只建立一个索引:

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

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

这在固定键时非常可靠。如果添加/删除键,则必须重建索引。


1
投票
不幸的是,由于在python中是如何构造字典的,所以这种事情是不可能的。这些数据结构本质上是

unordered。

要获得所需的功能,必须使用其他数据结构,例如OrderedDict

0
投票
对于python 3.6或更高版本,使用字典来保留插入顺序,那么您可以在一行中完成此操作,如果键不在字典中,则它返回'None':

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

© www.soinside.com 2019 - 2024. All rights reserved.