Created
August 4, 2013 18:42
-
-
Save kracekumar/6151391 to your computer and use it in GitHub Desktop.
Two Way Python dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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