hashtable - Efficient bidirectional hash table in Python? -


python dict useful datastructure:

d = {'a': 1, 'b': 2}  d['a'] # 1 

sometimes you'd index values.

d[1] # 'a' 

which efficient way implement datastructure? official recommend way it?

thanks!

here class bidirectional dict, inspired finding key value in python dictionary , modified allow following 2) , 3).

note :

  • 1) inverse directory bd.inverse auto-updates when standard dict bd modified
  • 2) inverse directory bd.inverse[value] list of key such bd[key] == value
  • 3) unlike bidict module https://pypi.python.org/pypi/bidict, here can have 2 keys having same value, very important.

code:

class bidict(dict):     def __init__(self, *args, **kwargs):         super(bidict, self).__init__(*args, **kwargs)         self.inverse = {}         key, value in self.iteritems():             self.inverse.setdefault(value,[]).append(key)       def __setitem__(self, key, value):         if key in self:             self.inverse[self[key]].remove(key)          super(bidict, self).__setitem__(key, value)         self.inverse.setdefault(value,[]).append(key)              def __delitem__(self, key):         self.inverse.setdefault(self[key],[]).remove(key)         if self[key] in self.inverse , not self.inverse[self[key]]:              del self.inverse[self[key]]         super(bidict, self).__delitem__(key) 

usage example:

bd = bidict({'a': 1, 'b': 2})   print bd                     # {'a': 1, 'b': 2}                  print bd.inverse             # {1: ['a'], 2: ['b']} bd['c'] = 1               # 2 keys have same value (= 1) print bd                     # {'a': 1, 'c': 1, 'b': 2} print bd.inverse             # {1: ['a', 'c'], 2: ['b']} del bd['c'] print bd                     # {'a': 1, 'b': 2} print bd.inverse             # {1: ['a'], 2: ['b']} del bd['a'] print bd                     # {'b': 2} print bd.inverse             # {2: ['b']} bd['b'] = 3 print bd                     # {'b': 3} print bd.inverse             # {2: [], 3: ['b']} 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -