2

I have a dictionary of objects:

dic = {'k1':obj1, 'k2':obj2, 'k3':obj3, ...}

class MyObject:
    def __init__(self,x,y):
        self.x=x
        self.y=y

I wonder how I can have the best implementation for finding the key that corresponds to a value. Something equivalent to:

def find_key(dic, val):
    for k,v in dic.items():
        if v==val:
            return k
    return None

NB: Sorry if this is obvious, I am a newbie in Python :-)

rds
  • 26,253
  • 19
  • 107
  • 134
  • 4
    what if multiple keys have that value? – samb8s Jul 19 '11 at 13:53
  • if you had googled it, you'd have found this too http://stackoverflow.com/questions/4504258/find-key-for-value-in-python-when-key-associated-with-multiple-values – samb8s Jul 19 '11 at 13:55
  • If you intend to reverse mappings often, I would suggest you look at the following questions on SO: http://stackoverflow.com/questions/863935/a-data-structure-for-11-mappings-in-python and http://stackoverflow.com/questions/1063319/reversible-dictionary-for-python - I don't know enough python to say for sure that you can not do better than what you wrote in your question, but I would be very surprised. – Jean Hominal Jul 19 '11 at 13:57
  • Sorry, I simplified the question, hence getting perfectly good answers that don't match my scenario: [I look for similar values](http://stackoverflow.com/questions/6749106/most-efficient-method-to-get-key-for-similar-values-in-a-dict) and not identical values – rds Jul 19 '11 at 14:47

4 Answers4

4

Ignoring the possibility that samb8s raises, that multiple keys exist for a single value, you can easily reverse the dictionary like this:

reverse_dic = dict((v, k) for k, v in dic.items())
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

You can use list comprehension. This code gives you the keys in a list:

>>> a
{1: 2, 3: 4, 9: 4, 5: 6, 7: 8}
>>> [key for key, value in a.items() if value == 4]
[3, 9]
utdemir
  • 26,532
  • 10
  • 62
  • 81
0

This will return a set of ALL keys that have that value - like a filter by value:

def find_keys(dic, val):
    return set(k for k,v in dic.items() if v == val)
Nate
  • 12,499
  • 5
  • 45
  • 60
0

regular dict[key] -> value

my_regular_dict = {1: 2, 3: 4, 5: 6}

reverse lookup, dict[value] -> key

my_reverse_lookup = dict([(val, key) for key, val in my_regular_dict.items()])
sampwing
  • 1,238
  • 1
  • 10
  • 13