>>>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
>>>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
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
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
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']
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
...:
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.
Perhaps it's too straightforward...
def val2key(dict, val):
for k, v in dict.items():
if v == val:
return k
return None
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']
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]