Is there a way to return the key for a match found in a dictionary using:
if val in dict.values():
# print the key of the value in the dictionary that matches val
I am trying to use the same search function, when looking for three different types of values. One is alphanumeric, the other is a string, and the third is a number. Within the search function I call the above code. In this function, I search through a dictionary containing known sets of these values (the three go together), trying to match the individual values read in from a file against these known sets in the dictionary. I have a search order (alphanumeric, string, number). The alphanumeric and number entries are one to one, but the string entry in the known dictionary is a list. I have been assuming that dict.iteritems()
would not search through the string list for the unknown string, but that val in dict.values()
would. Thus the use of the latter.
Depending on which matches (alphanumeric doesn't but number does, etc.), I wanted to return the key to know how the incoming data was matched against the known set.
So rather than writing two or three separate functions that for each key type, I was trying to use tricky dictionary code to keep it to one.
Edit:
So, suppose I have this dictionary:
dict = {'alphaNumeric':'A7', 'number':'36', 'string':['red','green','blue']}
and these incomplete sets of values to search against it:
sets = [['A7','',''],[['','36',''], ['','','green']]
I was trying to design on function to handle any searching:
def searchFun(sets, dict):
for set in sets:
for val in sets:
if val in dict.values():
return val, #KEY WHERE IT WAS FOUND#