Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 901
Rohita Khatiwada Avatar asked Aug 01 '11 11:08

Rohita Khatiwada


People also ask

Are dictionary entries ordered by position in Python?

In Python 3.7 and later versions, dictionaries are sorted by the order of item insertion. In earlier versions, they were unordered.

How do I sort an ordered dictionary in Python?

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.

How do you find the index of a dictionary?

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.

Are items in dictionary ordered?

In general dictionaries are not sorted. They are grouped by key/value pairs.


2 Answers

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 
like image 156
Michał Bentkowski Avatar answered Oct 06 '22 02:10

Michał Bentkowski


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).

like image 30
Amnon Harel Avatar answered Oct 06 '22 00:10

Amnon Harel