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?
In Python 3.7 and later versions, dictionaries are sorted by the order of item insertion. In earlier versions, they were unordered.
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.
Use the list[index] function to get index numbers from the dictionary. It will return the key and also use the items() function to return a collection from a dictionary.
In general dictionaries are not sorted. They are grouped by key/value pairs.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With