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

gwe*_*o10 6 python dictionary ordereddictionary

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

如果字典包括:

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

if 'test' in dictionary:
   print(the index of that key)
Run Code Online (Sandbox Code Playgroud)

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

我现在正在使用字典,我猜我必须使用命令dict才能执行此操作,但我怎么能使用有序的dict呢?

谢谢你的帮助.

Ste*_*ell 9

从 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'))
Run Code Online (Sandbox Code Playgroud)

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

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

for key in keys_of_interest:
    print('key: {}, index: {}'.format(key, key_list.index(key)))
Run Code Online (Sandbox Code Playgroud)

输出将是

key: test2, index: 1
key: test3, index: 2
Run Code Online (Sandbox Code Playgroud)


Aar*_*sen 8

对于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
Run Code Online (Sandbox Code Playgroud)

  • 这与 Python 3 中的工作方式并不完全相同,因为“OrderedDict.keys”返回“odict_keys”的实例而不是列表。我想,在 Python 3 中,必须先将其转换为元组或列表:`tuple(d.keys()).index('test3')` (2认同)
  • 这仅适用于Python <3.6.对于Python 3.6+,字典现在保留了插入顺序.请参阅[来自Python-Dev邮件列表的电子邮件](https://mail.python.org/pipermail/python-dev/2016-September/146327.html)以供讨论和示例. (2认同)

wnn*_*maw 0

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

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