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

36 投票
2 回答
45107 浏览
提问于 2025-04-16 22:39

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

举个例子:

如果我有一个字典:

// Ordered_dict is OrderedDictionary

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

那么我怎么知道cat在里面的位置呢?

有没有办法得到类似这样的答案:

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

2 个回答

6

对于Python3,你可以使用 tuple(d).index('animal') 这个代码。

这个方法和上面Marein的回答差不多,但它用的是不可改变的元组,而不是可以改变的列表。所以它的运行速度会稍微快一点(我简单测试了一下,大约快了12%)。

66

你可以通过 keys 属性来获取一个键的列表:

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

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

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

对于使用 Python 3 的朋友:

>>> list(d.keys()).index('animal')
2

撰写回答