无论您使用哪种解决方案,如果您希望它健壮,您可能应该在它周围包装一个类,当您更新一个时自动更新另一个方向。例如,这是一个使用@mgilson 技术的基本双向字典的开始(这意味着如果您要相互映射的两组项目之间有任何重叠,它将不起作用;但是,具有不同类型的效果很好):
class BiDict(dict):
"""Bidirectional Dictionary - setting 'key' to 'value' also
sets 'value' to 'key' (so don't use overlapping mappings)
"""
def __init__(self, *args):
super(BiDict, self).__init__(*args)
# After regular dict initialization, loop over any items
# and add their reverse. Note that we can't use any of the
# iter* methods here since we're adding items in the body
# of the loop.
for key in self.keys():
super(BiDict, self).__setitem__(self[key], key);
def __setitem__(self, key, val):
# If the key has an old value, delete its reverse
if key in self:
super(BiDict, self).__delitem__(self[key])
# Then add both forward and reverse for the new value
super(BiDict, self).__setitem__(key, val);
super(BiDict, self).__setitem__(val, key);
def __delitem__(self, key):
# delete both directions
if key in self:
super(BiDict, self).__delitem__(self[key]);
super(BiDict, self).__delitem__(key);
你可以像这样使用它:
>>> from bidict import BiDict
>>> d = BiDict({'a':1,'b':2})
>>> d['a']
1
>>> d[2]
'b'
>>> d['c']=3
>>> d[3]
'c'
>>> del d['a']
>>> d['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> d[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1