58

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
chapter3
  • 914
  • 2
  • 12
  • 21
  • What's wrong with `d['b']` ? – Anton Kovalenko Jan 26 '13 at 16:25
  • 4
    d['b'] will give you 20. But I actually want to get the position of the key in the dictionary which is 1. And I have the dictionary created as an ordered dictionary. – chapter3 Jan 26 '13 at 16:26
  • 2
    In dictionary, keys are unordered. So you could get any key while iterating the keys. – nsconnector Jan 26 '13 at 16:27
  • you can use ordereddict() from the collections package – chapter3 Jan 26 '13 at 16:29
  • 5
    If you have an ordered dict, then `d.keys().index(k)` should do it. – Felix Kling Jan 26 '13 at 16:36
  • Yes Felix, it works! Thanks a lot. Start getting tunnel visioning. Time to go to bed to get refreshed. :) – chapter3 Jan 26 '13 at 16:45
  • @FelixKling What version of Python are using? When I tried to that code, I got the error `AttributeError: 'KeysView' object has no attribute 'index'` – Seanny123 Dec 04 '13 at 03:14
  • 3
    @Seanny123 You didn't mention what version of Python *you* are using. Presumably it is Python 3, see http://www.python.org/dev/peps/pep-3106/ So, `list(d.keys()).index(k)`. Though hopefully there is a better solution in Python 3, that doesn't require creating a list of all the keys... – ToolmakerSteve Dec 10 '13 at 19:37

5 Answers5

96

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
nu everest
  • 9,589
  • 12
  • 71
  • 90
Kiwisauce
  • 1,229
  • 8
  • 7
  • 2
    Good solution but , im wondering the complexity of getting the index (might be O(n)) . can we get key-value pair by the index value > or atleast key or value. – yunus Oct 30 '18 at 11:36
  • Also consider Pandas [`dataframe`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) for this use-case, especially if you need to be able to drop items while the assigned index locations remain fixed (i.e. a dropped item creates a 'hole' in the data structure), or if you need to be able to have multiple items in the structure with the same "key" (obviously it is not a real key in such case). – Ville Mar 18 '19 at 01:58
  • The `.keys()` is optional btw. Just `list(x).index("c")` also works. – Janosh Mar 21 '22 at 20:35
  • .keys().index(...) doesn't work at least for python3, so I used list(x).index("c") which is probably less efficient because it uses a list instead of an iterator, but it works – herve-guerin Aug 28 '22 at 10:23
4

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]
Jahid
  • 21,542
  • 10
  • 90
  • 108
Matt Alcock
  • 12,399
  • 14
  • 45
  • 61
  • 1
    Ur answer is correct but the complexity of serching or inserting is high . That is the reson ppl use dictionay , orderedDict is similar to hashtable in java . – yunus Oct 30 '18 at 05:21
2

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'))
Nick W.
  • 1,536
  • 3
  • 24
  • 40
1

No, in Python 2 there is no straightforward way because dictionaries in that version do not have a set ordering (you need Python 3.6 or newer for that, 3.7 if it is not a cpython implementation).

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    For anyone stumbling upon this: Since python 3.7, dictionary iteration order is now guaranteed to be in order of insertion. – Banana May 19 '22 at 11:53
  • @Banana: yes, but the question _here_ is tagged with Python 2.7, which never got the new dictionary implementation. – Martijn Pieters May 19 '22 at 16:37
  • question is tagged as both `python` and `python-2.7`, and the words "python 2.7" are not directly specified anywhere in the question, therefore @Banana's comment is valid – Fnord May 26 '23 at 23:30
  • @Fnord: using the 2.7 tag **makes the question specific to 2.7**; at the time this answer was written, to get python 3.x answers we'd use the [tag:python-3.x] tag. – Martijn Pieters Jun 08 '23 at 17:35
1
#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 :)
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Se7enstars
  • 21
  • 1