如果字典中存在键,我想知道该键在数字索引中的位置。例如:
如果字典包含:
{'test':{1,3},'test2':{2},'test3':{2,3}}
if 'test' in dictionary:
print(the index of that key)
例如,输出为0。 (对于“ test3”,输出为2。)
[我目前正在使用字典,我想我必须使用有序dict
来执行此操作,但是如何使用有序dict
来执行此操作?
感谢您的帮助。
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
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
ind= {k:i for i,k in enumerate(dictionary.keys())}
然后ind['test3']
将为2,具有O(1)访问时间。这在固定键时非常可靠。如果添加/删除键,则必须重建索引。
unordered。
要获得所需的功能,必须使用其他数据结构,例如OrderedDictkey_index = list(my_dictionary).index(the_key) if the_key in my_dictionary else None