3
>>>Dictionary[key]

The above statement returns the first corresponding value of the 'key' from the 'Dictionary' but is there a function that does the opposite, i.e. search for the key by it's value

Taher Elhouderi
  • 233
  • 2
  • 11

8 Answers8

2

Just iterate over the dictionary items and check for the value with your string. If it matches then print it's corresponding key.

>>> d = {'foo':1,'bar':2}
>>> for k,v in d.items():
        if v == 1:
            print(k)


foo
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

You can write simple lambda for this:

d={"a":5, "bf": 55, "asf": 55}

search_key = lambda in_d, val: (k for k,v in in_d.items() if v == val)

for k in search_key(d, 55):
    print(k)

# since the lambda returns generator expression you can simply print
# the keys as follows:

print(list(search_key(d, 55)))  
# or get the key list
key_list = list(search_key(d, 55))

Gives:

asf
bf
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • I'd use a list comprehension rather than a generator for later use. – Malik Brahimi Feb 20 '15 at 01:17
  • @MalikBrahimi if the dict is very large, generator would be better as you dont need to make a full list at once, or when only first matching key is of interest rather than all possible keys. In the second case you would just write `first_key = next(search_key(d, 55))`. – Marcin Feb 20 '15 at 01:22
1

There's no single function, but it's easy to get the (possibly multiple) keys for a particular value:

>>> d = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 0, 'g': 1}
>>> [k for k, v in d.items() if v == 1]
['b', 'g']
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
1

i don't think you can, but you can do this

In [3]: dict_1 = {1:"one", 2:"two"}

In [4]: for number, alphabet in dict_1.items():
   ...:     if alphabet == "two":
   ...:         print number
   ...: 
demo.b
  • 3,299
  • 2
  • 29
  • 29
1

For this you can work with .keys() and .values(), which will return a list of keys or values respectivley. These lists can be easily iterated over and searched.

An example with a simple dictionary:

>>> D1 = {'A':1, 'B':2, 'C':1}
>>> D1['A']
1

>>> for key in D1.keys():
        if D1[key] == 1:
            print(key)
C
A

As Padraic Cunningham pointed out, a key must be unique, but a value does not, so you run into problems when you have multiple keys that match 1 value.

Malonge
  • 1,980
  • 5
  • 23
  • 33
1

Perhaps it's too straightforward...

def val2key(dict, val):
    for k, v in dict.items():
        if v == val:
            return k
    return None         
constt
  • 2,250
  • 1
  • 17
  • 18
1

Trivial, using list comprehensions:

>>> d = {'a': 1, 'b': 2, 'c': 1}
>>> l = [k for k, v in d.items() if v == 1]
>>> l
['c', 'a']
Alexandre Bell
  • 3,141
  • 3
  • 30
  • 43
0

Use a list comprehension and substitute the name of your dictionary and the desired value.

keys = [k for k, v in my_dict.items() if v == my_value]
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70