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

例如:

如果我有字典:

// Ordered_dict is OrderedDictionary

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

现在我如何知道cat属于哪个位置?
是否有可能得到如下答案:
position (Ordered_dict["animal"]) = 2 ?还是其他方式?

最佳答案

您可能会获得带有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

关于python - 如何知道项目在Python有序字典中的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6897750/

10-11 07:22
查看更多