Reputation: 65
Suppose I have a dictionary
d={'name1': ['A1', 'A2', 'A3', 'A4'], 'name2': ['E1', 'F1', 'G1'], 'name3'=['E3','F3']}
How can I get the key of a specific value. For example, input='A1' then output='name1'. I was thinking to create a function like below, but it might not working (return None) because of the list in dictionary
def reverse_search(dictionary, value):
keys = dictionary.keys()
for key in keys:
if dictionary.get(key) == value:
return key
I really appreciate any help!
Upvotes: 0
Views: 678
Reputation: 356
I think the easiest way like this
d = {'name1': ['A1', 'A2', 'A3', 'A4'],
'name2': ['E1', 'F1', 'G1'],
'name3': ['E3', 'F3']
}
def filter_dict(search_key):
k, v = tuple(filter(lambda x: search_key in x[1], d.items()))[0]
return k
search_key = 'A1'
print(filter_dict(search_key))
Upvotes: 1
Reputation: 3356
try below code:
d = {'name1': ['A1', 'A2', 'A3', 'A4'],'name2': ['E1', 'F1', 'G1'], 'name3' : ['E3', 'F3']}
s = 'A1'
o = list(filter(lambda x:s in x[1],d.items()))[0][0]
print(o)
Upvotes: 1
Reputation: 59444
It is more performant to construct a reverse dictionary first if you are going to do this multiple times:
>>> reverse_lookup = {k: v for v, l in d.items() for k in l}
then
>>> reverse_lookup['A1']
'name1'
>>> reverse_lookup['G1']
'name2'
Upvotes: 1
Reputation: 83
You can check in list if that value exists:
def reverse_search_from_dictionary(dictionary, value):
keys = dictionary.keys()
for key in keys:
if value in dictionary.get(key):
return key
return "Not present"
Upvotes: 1
Reputation: 54168
You're near to get it, but the dict's values are list
so you can't use ==
, because ['A1', 'A2', 'A3', 'A4'] != 'A1'
you need to test for inclusion with in
def reverse_search_from_dictionary(dictionary, value):
keys = dictionary.keys()
for key in keys:
if value in dictionary[key]: # no need of 'get', you're sure the key is present
return key
Nicer with iteration on both pairs and values
def reverse_search_from_dictionary(dictionary, keyword):
for key, values in dictionary.items():
if keyword in values:
return key
Upvotes: 4