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

2024-10-05 14:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

如果我有字典:

// Ordered_dict is OrderedDictionary

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

现在我如何知道cat属于哪个位置? 有没有可能得到这样的答案:

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


Tags: 项目答案字典ispositiondictcatbanana
3条回答

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

class collections.OrderedDict([items]) - Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

New in version 2.7.

因此,如果你使用的是一个有序的字典,你不会删除键-然后'动物'将永远在你添加的位置-例如索引2。

此外,要获得“猫”的索引,您可以简单地使用:

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

您可以获得具有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

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

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

相关问题 更多 >