How to know the position of items in a Python ordered dictionary

拥有回忆 提交于 2019-12-09 14:00:26

问题


Can we know the position of items in Python's ordered dictionary?

For example:

If I have dictionary:

// Ordered_dict is OrderedDictionary

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

Now how do I know in which position cat belongs to? Is it possible to get an answer like:

position (Ordered_dict["animal"]) = 2 ? or in some other way?


回答1:


You may get a list of keys with the keys property:

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

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

Better performance could be achieved with the use of iterkeys() though.

For those using Python 3:

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



回答2:


For Python3: tuple(d).index('animal')

This is almost the same as Marein's answer above, but uses an immutable tuple instead of a mutable list. So it should run a little bit faster (~12% faster in my quick sanity check).




回答3:


Think first that you need to read documentation. If you open a Python tutorial and then try to find information about OrderedDict you will see the following:

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.

So in case you are using an ordered dictionary and you are not going to delete keys - then 'animal' will be always in the position you add - e.g. index 2.

Also to get an index of a 'cat' you can simply use:

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


来源:https://stackoverflow.com/questions/6897750/how-to-know-the-position-of-items-in-a-python-ordered-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!