Back to index

salome-kernel  6.5.0
diclookup.py
Go to the documentation of this file.
00001 # -*- coding: iso-8859-1 -*-
00002 # Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00003 #
00004 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00005 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00006 #
00007 # This library is free software; you can redistribute it and/or
00008 # modify it under the terms of the GNU Lesser General Public
00009 # License as published by the Free Software Foundation; either
00010 # version 2.1 of the License.
00011 #
00012 # This library is distributed in the hope that it will be useful,
00013 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00014 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015 # Lesser General Public License for more details.
00016 #
00017 # You should have received a copy of the GNU Lesser General Public
00018 # License along with this library; if not, write to the Free Software
00019 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00020 #
00021 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00022 #
00023 
00024 __author__="gboulant"
00025 __date__ ="$21 mai 2010 18:00:23$"
00026 
00027 
00028 # search a dictionary for key or value
00029 # using named functions or a class
00030 # tested with Python25   by Ene Uran    01/19/2008
00031 
00032 def find_key(dic, val):
00033     """return the key of dictionary dic given the value"""
00034     return [k for k, v in dic.iteritems() if v == val][0]
00035 
00036 def find_value(dic, key):
00037     """return the value of dictionary dic given the key"""
00038     return dic[key]
00039 
00040 class Lookup(dict):
00041     """
00042     a dictionary which can lookup value by key, or keys by value
00043     """
00044     def __init__(self, items=[]):
00045         """items can be a list of pair_lists or a dictionary"""
00046         dict.__init__(self, items)
00047 
00048     def get_keys(self, value):
00049         """find the key(s) as a list given a value"""
00050         return [item[0] for item in self.items() if item[1] == value]
00051 
00052     def get_key(self, value):
00053         """
00054         find the key associated to the given a value. If several keys exist,
00055         only the first is given. To get the whole list, use get_keys instead.
00056         """
00057         list = self.get_keys(value)
00058         if len(list) == 0:
00059             return None
00060         return list[0]
00061 
00062     def get_value(self, key):
00063         """find the value given a key"""
00064         return self[key]
00065 
00066 #
00067 # ==============================================================================
00068 # Use cases and unit tests
00069 # ==============================================================================
00070 #
00071 def TEST_getTestDictionnary():
00072     # dictionary of chemical symbols
00073     symbol_dic = {
00074     'C': 'carbon',
00075     'H': 'hydrogen',
00076     'N': 'nitrogen',
00077     'Li': 'lithium',
00078     'Be': 'beryllium',
00079     'B': 'boron'
00080     }
00081     return symbol_dic
00082 
00083 def TEST_find_value():
00084     symbol_dic = TEST_getTestDictionnary()
00085     print find_key(symbol_dic, 'boron')  # B
00086     print find_value(symbol_dic, 'B')    # boron
00087     print find_value(symbol_dic, 'H')    # hydrogen
00088     if find_key(symbol_dic, 'nitrogen') != 'N':
00089         return False
00090     return True
00091 
00092 def TEST_lookup():
00093     symbol_dic = TEST_getTestDictionnary()
00094 
00095     name = 'lithium'
00096     symbol = 'Li'
00097     # use a dictionary as initialization argument
00098     look = Lookup(symbol_dic)
00099     print look.get_key(name)      # [Li']
00100     if look.get_key(name) != symbol:
00101         print "get "+str(look.get_key(name))+" while "+str(symbol)+" was expected"
00102         return False
00103     print look.get_value(symbol)  # lithium
00104 
00105     # use a list of pairs instead of a dictionary as initialization argument
00106     # (will be converted to a dictionary by the class internally)
00107     age_list = [['Fred', 23], ['Larry', 28], ['Ene', 23]]
00108     look2 = Lookup(age_list)
00109     print look2.get_keys(23)        # ['Ene', 'Fred']
00110     if look2.get_keys(23)[0] != 'Ene' or look2.get_keys(23)[1] != 'Fred':
00111         print "get "+str(look2.get_keys(23))+" while ['Ene', 'Fred'] was expected"
00112         return False
00113     print look2.get_value('Fred')  # 23
00114     return True
00115 
00116 if __name__ == '__main__':
00117     import unittester
00118     unittester.run("diclookup", "TEST_find_value")
00119     unittester.run("diclookup", "TEST_lookup")