首先,你需要阅读文档。如果打开一个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