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

Question:

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.

Asked By: chapter3

||

Answers:

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the ‘index’ of b depends entirely on what was inserted into and deleted from the mapping before:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

Answered By: Martijn Pieters

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
Answered By: Kiwisauce

Dictionaries in python (<3.6) have no order. You could use a list of tuples as your data structure instead.

d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]

Then this code could be used to find the locations of keys with a specific value

locations = [i for i, t in enumerate(newd) if t[0]=='b']

>>> [1]
Answered By: Matt Alcock
#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}

#Convert dictionary to list (array)
keys = list(animals)

#Printing 1st dictionary key by index
print(keys[0])

#Done :)
Answered By: Se7enstars

You can simply send the dictionary to list and then you can select the index of the item you are looking for.

DictTest = {
    '4000':{},
    '4001':{},
    '4002':{},
    '4003':{},
    '5000':{},
}

print(list(DictTest).index('4000'))
Answered By: Nick W.