Most commonly a dictionary of key:value pairs is searched by the unique key. Sometimes it becomes necessary to search for the key, or keys given a value. Special consideration has to be given to this case, because the value does not have to be unique and may return several keys (list of keys).

A class inheriting the dictionary base class is used to do both searches. I have also made up some simple, but nicely named functions to search the dictionary, in case you don't want to use a class.

# search a dictionary for key or value
# using named functions or a class
# tested with Python25   by Ene Uran    01/19/2008

def find_key(dic, val):
    """return the key of dictionary dic given the value"""
    return [k for k, v in symbol_dic.iteritems() if v == val][0]

def find_value(dic, key):
    """return the value of dictionary dic given the key"""
    return dic[key]

class Lookup(dict):
    a dictionary which can lookup value by key, or keys by value
    def __init__(self, items=[]):
        """items can be a list of pair_lists or a dictionary"""
        dict.__init__(self, items)

    def get_key(self, value):
        """find the key(s) as a list given a value"""
        return [item[0] for item in self.items() if item[1] == value]

    def get_value(self, key):
        """find the value given a key"""
        return self[key]

# test it out
if __name__ == '__main__':
    # dictionary of chemical symbols
    symbol_dic = {
    'C': 'carbon',
    'H': 'hydrogen',
    'N': 'nitrogen',
    'Li': 'lithium',
    'Be': 'beryllium',
    'B': 'boron'

    print find_key(symbol_dic, 'boron')  # B
    print find_value(symbol_dic, 'B')    # boron
    print find_value(symbol_dic, 'H')    # hydrogen
    name = 'lithium'
    symbol = 'Li'
    # use a dictionary
    look = Lookup(symbol_dic)
    print look.get_key(name)      # [Li']
    print look.get_value(symbol)  # lithium
    # use a list of pairs instead of a dictionary
    # will be converted to a dictionary by the class internally
    age_list = [['Fred', 23], ['Larry', 28], ['Ene', 23]]
    look2 = Lookup(age_list)
    print look2.get_key(23)        # ['Ene', 'Fred']
    print look2.get_value('Fred')  # 23
9 Years
Discussion Span
Last Post by Lucaci Andrew

Much thanks! Your code is very helpful (and efficient too!) :)

However, in defining "find_key", shouldn't you use the argument "dic" instead of "symbol_dic" in calling iteritems? :)

Other than that, thanks for the big help! :)


I have a dictionary. when user enters a word, i need my program search in that dictionary and find the correct value and print it. Please see the image.. this is my code. it will give correct output when we enter a word which the dictionary have. Please guide me.

Attachments dict.JPG 71.71 KB

Here's a small example:

# en to de
trans = {
    "house" : "haus",
    "car"   : "auto",
    "food"  : "lebensmittel",
    "sleep" : "schlaf"

while True:
    ans = raw_input("Translate: ")
    if ans == "quit": break
    print trans[ans] if ans in trans else "Invalid word."

Basically, you search for the given word to see if it's a key in your dictionary, and if it is, you print the corresponding value, or an error message.
if ans in trans checks if a given string is a key in a dictionary.
trans[ans] if ans in trans else "Invalid word." is used as a ternary operator in other languages e.g. `# result = condition ? if_condition_true : if_condition_false

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.