Salome HOME
f107e93a8e68f483182ed0f12da6ea3d63468e7c
[modules/kernel.git] / src / KERNEL_PY / kernel / diclookup.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
3 #
4 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23
24 ## \defgroup diclookup diclookup
25 #  \{ 
26 #  \details Smart dictionary with key/value lookup
27 #  \}
28
29 __author__="gboulant"
30 __date__ ="$21 mai 2010 18:00:23$"
31
32
33 # search a dictionary for key or value
34 # using named functions or a class
35 # tested with Python25   by Ene Uran    01/19/2008
36
37 ## return the key of dictionary dic given the value
38 #  \ingroup diclookup
39 def find_key(dic, val):
40     """return the key of dictionary dic given the value"""
41     return [k for k, v in dic.items() if v == val][0]
42
43 ## return the value of dictionary dic given the key
44 #  \ingroup diclookup
45 def find_value(dic, key):
46     """return the value of dictionary dic given the key"""
47     return dic[key]
48
49 ## a dictionary which can lookup value by key, or keys by value
50 #  \ingroup diclookup
51 class Lookup(dict):
52     """
53     a dictionary which can lookup value by key, or keys by value
54     """
55     ## items can be a list of pair_lists or a dictionary
56     def __init__(self, items=None):
57         """items can be a list of pair_lists or a dictionary"""
58         if items is None:
59             items = []
60         dict.__init__(self, items)
61
62     ## find the key(s) as a list given a value
63     def get_keys(self, value):
64         """find the key(s) as a list given a value"""
65         return [item[0] for item in list(self.items()) if item[1] == value]
66
67     ## find the key associated to the given a value. If several keys exist,
68     #  only the first is given. To get the whole list, use get_keys instead.
69     def get_key(self, value):
70         """
71         find the key associated to the given a value. If several keys exist,
72         only the first is given. To get the whole list, use get_keys instead.
73         """
74         list = self.get_keys(value)
75         if len(list) == 0:
76             return None
77         return list[0]
78
79     ## find the value given a key
80     def get_value(self, key):
81         """find the value given a key"""
82         return self[key]
83
84 #
85 # ==============================================================================
86 # Use cases and unit tests
87 # ==============================================================================
88 #
89 def TEST_getTestDictionnary():
90     # dictionary of chemical symbols
91     symbol_dic = {
92     'C': 'carbon',
93     'H': 'hydrogen',
94     'N': 'nitrogen',
95     'Li': 'lithium',
96     'Be': 'beryllium',
97     'B': 'boron'
98     }
99     return symbol_dic
100
101 def TEST_find_value():
102     symbol_dic = TEST_getTestDictionnary()
103     print(find_key(symbol_dic, 'boron'))  # B
104     print(find_value(symbol_dic, 'B'))    # boron
105     print(find_value(symbol_dic, 'H'))    # hydrogen
106     if find_key(symbol_dic, 'nitrogen') != 'N':
107         return False
108     return True
109
110 def TEST_lookup():
111     symbol_dic = TEST_getTestDictionnary()
112
113     name = 'lithium'
114     symbol = 'Li'
115     # use a dictionary as initialization argument
116     look = Lookup(symbol_dic)
117     print(look.get_key(name))      # [Li']
118     if look.get_key(name) != symbol:
119         print("get "+str(look.get_key(name))+" while "+str(symbol)+" was expected")
120         return False
121     print(look.get_value(symbol))  # lithium
122
123     # use a list of pairs instead of a dictionary as initialization argument
124     # (will be converted to a dictionary by the class internally)
125     age_list = [['Fred', 23], ['Larry', 28], ['Ene', 23]]
126     look2 = Lookup(age_list)
127     print(look2.get_keys(23))        # ['Ene', 'Fred']
128     if look2.get_keys(23)[0] != 'Ene' or look2.get_keys(23)[1] != 'Fred':
129         print("get "+str(look2.get_keys(23))+" while ['Ene', 'Fred'] was expected")
130         return False
131     print(look2.get_value('Fred'))  # 23
132     return True
133
134 if __name__ == '__main__':
135     from . import unittester
136     unittester.run("diclookup", "TEST_find_value")
137     unittester.run("diclookup", "TEST_lookup")