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

问题描述 投票:32回答:3

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

例如:

如果我有字典:

// Ordered_dict is OrderedDictionary

Ordered_dict = {"fruit": "banana", "drinks": "water", "animal": "cat"}

现在我怎么知道cat属于哪个位置?是否有可能得到如下答案:

position (Ordered_dict["animal"]) = 2 ?或以其他方式?

python ordereddictionary
3个回答
60
投票

您可以使用keys属性获取密钥列表:

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

In [21]: d.keys().index('animal')
Out[21]: 2

但是,使用iterkeys()可以获得更好的性能。

对于那些使用Python 3的人:

>>> list(x.keys()).index("c")
1

4
投票

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

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


3
投票

首先想一想你需要阅读文档。如果您打开Python教程然后尝试查找有关OrderedDict的信息,您将看到以下内容:

class collections.OrderedDict([items]) - 返回一个dict子类的实例,支持通常的dict方法。 OrderedDict是一个dict,它记住了第一次插入键的顺序。如果新条目覆盖现有条目,则原始插入位置保持不变。删除条目并重新插入它将使其移至最后。

版本2.7中的新功能。

因此,如果您使用的是有序字典并且您不打算删除密钥 - 那么“动物”将始终处于您添加的位置 - 例如指数2。

另外,要获得'cat'的索引,您只需使用:

from collections import OrderedDict
d = OrderedDict((("fruit", "banana"), ("drinks", "water"), ("animal", "cat")))
d.keys()
>>> ['fruit', 'drinks', 'animal']
d.values()
>>> ['banana', 'water', 'cat']
# So
d.values().index('cat')
>>> 2
© www.soinside.com 2019 - 2024. All rights reserved.