Search code examples
pythonpython-2.7dictionaryindexingkey

How to get the index with the key in a dictionary?


I have the key of a python dictionary and I want to get the corresponding index in the dictionary. Suppose I have the following dictionary,

d = { 'a': 10, 'b': 20, 'c': 30}

Is there a combination of python functions so that I can get the index value of 1, given the key value 'b'?

d.??('b') 

I know it can be achieved with a loop or lambda (with a loop embedded). Just thought there should be a more straightforward way.


Solution

  • Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict

    >>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
    >>> x["d"] = 4
    >>> x.keys().index("d")
    3
    >>> x.keys().index("c")
    1
    

    For those using Python 3

    >>> list(x.keys()).index("c")
    1