沒問題,你應該環繞它的一類,當你更新一個自動更新的另一個方向。例如,下面是使用@ 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
什麼是您反對有兩個詞典?只要你從另一個自動生成一個,而不是獨立地定義它們,它似乎是最直接的解決方案。 –
@MarkReed,聽起來有點不對。我是Python的新手,我認爲創建一個實際上可以反向查找字典的實體會更好。就這樣。你認爲這樣嗎? – Phil