Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get key of index in dictionary [duplicate]

Tags:

Possible Duplicate:
Inverse dictionary lookup - Python
reverse mapping of dictionary with Python

How do i get key of index in dictionary?

For example like:

i = {'a': 0, 'b': 1, 'c': 2} 

so if i want to get key of i[0], it will return 'a'

like image 472
Natsume Avatar asked Jul 24 '12 14:07

Natsume


People also ask

Can KEY be repeated in dictionary python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can key in dictionary have duplicate values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

You could do something like this:

i={'foo':'bar', 'baz':'huh?'} keys=i.keys()  #in python 3, you'll need `list(i.keys())` values=i.values() print keys[values.index("bar")]  #'foo' 

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1} 

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

like image 157
mgilson Avatar answered Sep 30 '22 03:09

mgilson