Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Created August 4, 2013 18:42
Show Gist options
  • Save kracekumar/6151391 to your computer and use it in GitHub Desktop.
Save kracekumar/6151391 to your computer and use it in GitHub Desktop.
Two Way Python dict
class TwoWayDict(dict):
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
if value in self:
if isinstance(dict.__getitem__(self, value), list):
self[value].append(key)
else:
dict.__setitem__(self, value, [key])
In [88]: t = TwoWayDict()
In [89]: t['a'] = 1
In [90]: t['b'] = 1
In [91]: t['c'] = 1
In [92]: t
Out[92]: {1: ['a', 'b', 'c'], 'a': 1, 'b': 1, 'c': 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment