getting the key index in a Python OrderedDict?

后端 未结 3 2003
慢半拍i
慢半拍i 2020-12-10 11:52

I have a collections.OrderedDict with a list of key, value pairs. I would like to compute the index i such that the ith key matches a given value.

3条回答
  •  悲&欢浪女
    2020-12-10 12:21

    The OrderedDict is a subclass of dict which has the ability to traverse its keys in order (and reversed order) by maintaining a doubly linked list. So it does not know the index of a key. It can only traverse the linked list to find the items in O(n) time.

    Perusing the source code may be the most satisfying way to confirm that the index is not maintained by OrderedDict. You'll see that no where is an index ever used or obtained.

提交回复
热议问题