Greg Clayton | 6a23d21 | 2013-09-04 17:31:40 +0000 | [diff] [blame] | 1 | |
| 2 | class LookupDictionary(dict): |
| 3 | """ |
| 4 | a dictionary which can lookup value by key, or keys by value |
| 5 | """ |
| 6 | def __init__(self, items=[]): |
| 7 | """items can be a list of pair_lists or a dictionary""" |
| 8 | dict.__init__(self, items) |
| 9 | |
| 10 | def get_keys_for_value(self, value, fail_value = None): |
| 11 | """find the key(s) as a list given a value""" |
| 12 | list_result = [item[0] for item in self.items() if item[1] == value] |
| 13 | if len(list_result) > 0: |
| 14 | return list_result |
| 15 | return fail_value |
| 16 | |
| 17 | def get_first_key_for_value(self, value, fail_value = None): |
| 18 | """return the first key of this dictionary given the value""" |
| 19 | list_result = [item[0] for item in self.items() if item[1] == value] |
| 20 | if len(list_result) > 0: |
| 21 | return list_result[0] |
| 22 | return fail_value |
| 23 | |
| 24 | def get_value(self, key, fail_value = None): |
| 25 | """find the value given a key""" |
| 26 | if key in self: |
| 27 | return self[key] |
| 28 | return fail_value |
| 29 | |
| 30 | |
| 31 | class Enum(LookupDictionary): |
| 32 | |
| 33 | def __init__(self, initial_value=0, items=[]): |
| 34 | """items can be a list of pair_lists or a dictionary""" |
| 35 | LookupDictionary.__init__(self, items) |
| 36 | self.value = initial_value |
| 37 | |
| 38 | def set_value(self, v): |
| 39 | v_typename = typeof(v).__name__ |
| 40 | if v_typename == 'str': |
| 41 | if str in self: |
| 42 | v = self[v] |
| 43 | else: |
| 44 | v = 0 |
| 45 | else: |
| 46 | self.value = v |
| 47 | |
| 48 | def get_enum_value(self): |
| 49 | return self.value |
| 50 | |
| 51 | def get_enum_name(self): |
| 52 | return self.__str__() |
| 53 | |
| 54 | def __str__(self): |
| 55 | s = self.get_first_key_for_value (self.value, None) |
| 56 | if s == None: |
| 57 | s = "%#8.8x" % self.value |
| 58 | return s |
| 59 | |
| 60 | def __repr__(self): |
| 61 | return self.__str__() |