Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 318
chapter3 Avatar asked Jan 26 '13 16:01

chapter3


People also ask

Does dictionary keys have index in Python?

The Python Dictionary object provides a key:value indexing facility. Note that dictionaries are unordered - since the values in the dictionary are indexed by keys, they are not held in any particular order, unlike a list, where each item can be located by its position in the list.

Are Keys in dictionary indexed?

In dictionary, keys are unordered.

Does dictionary have index?

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.


1 Answers

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 
like image 55
Kiwisauce Avatar answered Sep 30 '22 16:09

Kiwisauce