rds
rds

Reputation: 26984

Most efficient method to get key for a value in a dict

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 :-)

Upvotes: 2

Views: 1408

Answers (4)

sampwing
sampwing

Reputation: 1268

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()])

Upvotes: 0

utdemir
utdemir

Reputation: 27216

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]

Upvotes: 1

Nate
Nate

Reputation: 12819

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)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599510

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())

Upvotes: 6

Related Questions