如何知道Python有序字典中项目的位置

Roh*_*ada 33 python ordereddictionary

我们能否知道Python有序字典中项目的位置?例如:

如果我有字典:

// Ordered_dict is OrderedDictionary

Ordered_dict = {"fruit": "banana", "drinks": "water", "animal": "cat"}
Run Code Online (Sandbox Code Playgroud)

现在如何知道猫属于哪个位置?是否有可能得到如下答案:

cat 或以其他方式?

Mic*_*ski 62

您可以获得keys属性的密钥列表:

In [20]: d=OrderedDict((("fruit", "banana"), ("drinks", 'water'), ("animal", "cat")))

In [21]: d.keys().index('animal')
Out[21]: 2
Run Code Online (Sandbox Code Playgroud)

使用iterkeys()虽然可以实现更好的性能.

对于那些使用Python 3的人

>>> list(d.keys()).index('animal')
2
Run Code Online (Sandbox Code Playgroud)

  • `list(d.keys()).index('animal')`适合任何使用**Python3**的人在这里结束. (29认同)
  • 似乎只使用`list(d).index('animal')`也适用于Python 3,除非我遗漏了一些东西. (6认同)

小智 6

对于 Python3: tuple(d).index('animal')

这与上面 Marein 的答案几乎相同,但使用不可变元组而不是可变列表。所以它应该运行得更快一点(在我的快速健全性检查中快了大约 12%)。