0

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#
traggatmot
  • 1,423
  • 5
  • 26
  • 51
  • 4
    There is no guarantee there is such a thing as "the" key, since multiple keys may have the same value. What do you want to happen in that case? – BrenBarn Nov 22 '15 at 07:38
  • 1
    Possible duplicate of [How can you print a key given a value in a dictionaty for Python?](http://stackoverflow.com/questions/15784590/how-can-you-print-a-key-given-a-value-in-a-dictionaty-for-python) – Avihoo Mamka Nov 22 '15 at 07:39
  • The way my dictionary and larger functions are set up, duplicates are not a possibility. If the value is found, it will be associated with only one key. – traggatmot Nov 22 '15 at 07:40
  • Possible duplicate of [Finding key from value in Python dictionary:](http://stackoverflow.com/questions/7657457/finding-key-from-value-in-python-dictionary) – Remi Guan Nov 22 '15 at 07:49
  • 1
    Keep in mind that using the value to look up a key is the opposite of how dictionaries are supposed to work. You've probably got an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Nov 22 '15 at 08:02
  • does it still appear that way after my edits? It seems to me that it may not be. – traggatmot Nov 22 '15 at 08:06
  • 1
    Yes, it still does appear so. – TigerhawkT3 Nov 22 '15 at 08:34

4 Answers4

2

You are using dictionaries backwards. You will have an easier time if you arrange them in the other direction:

my_dict = {'A7':'alphaNumeric', '36':'number', 'red':'string', 'green':'string', 'blue':'string'}
my_queries = ['A7', '', '', '', '36', '', '', '', 'green']

Note that your list of queries, being an irregular multi-dimensional list, should be flattened (there's a good method for that in the top answer in this question - you can tweak it to suit your version of Python if necessary). I've hard-coded it as a flat list to demonstrate the lookup function.

Now you can use a clean, concise function:

def searchfun(d, queries):
    return [(key,d[key]) for key in queries if key in d]

With the following result:

>>> searchfun(my_dict, my_queries)
[('A7', 'alphaNumeric'), ('36', 'number'), ('green', 'string')]

Also note that this is similar to OOP, with each object having an attribute that might be called something like self.classification.

Community
  • 1
  • 1
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Wow. That's really interesting. If I am using them backwards, are many others? May seem to follow attribute:value, instead of value:attribute. For instance, this site: http://www.tutorialspoint.com/python/python_dictionary.htm , has attribute:value suggested. And I feel like I've seem many others like that. – traggatmot Nov 22 '15 at 08:47
  • 2
    @traggatmot - You'll have to evaluate it on a case-by-case basis, but generally you should consider which information you _have_ and which information you _want_, then go in that direction. Looking up a certain attribute for a bunch of values/objects? `value:attribute`. Finding all the values that have a certain attribute? `attribute:[value1, value2]`. – TigerhawkT3 Nov 22 '15 at 09:06
0

Dictionaries are optimized to find the keys. There's no good way to look up by value. You just have to iterate it.

for k, v in dict.iteritems():
    if val == v:
        print k
Laizer
  • 5,932
  • 7
  • 46
  • 73
  • Lists only compare as `True` if they are in the same order. If you need to compare lists that may be in different orders, you can use set(val) == set(v). A gotcha: It will eliminate any duplicates in the comparison. – Laizer Nov 22 '15 at 07:44
0

No, there isn't. As @Laizer suggests, you can use .iteritems (or .items() in python3. But you can't do it with .values(). You could return one of the keys with that value however:

if val in dict.values():
    for k in dict.keys(): # of just `for x in dict:`
        if val == dict[k]:
             print k
NotAnAmbiTurner
  • 2,553
  • 2
  • 21
  • 44
  • How might this change when one of the values is a list of strings? – traggatmot Nov 22 '15 at 07:52
  • It shouldn't change at all, as long as the lists match, they match. – NotAnAmbiTurner Nov 22 '15 at 07:55
  • You misunderstand. Sorry for my poor explanation. if I have an unknown string that is read in, I comparing it to a part of the dictionary (the string part) in which the value is a list - it's not list to list comparison, but attempting to see if the string (if that is the data read in) is in the list. – traggatmot Nov 22 '15 at 07:57
0

There is no direct method to identify key based on values as multiple keys can have same value such as

mydict = {'orange': 0, 'red': 1, 'yellow': 2, 'black': 0}
print mydict.keys()[mydict.values().index(0)]

This will return you the first occurrence value 0 key that is 'orange'

Shreeyansh Jain
  • 1,407
  • 15
  • 25