A couple of years ago, @Emile Schwarz asked about a two-way dictionary: https://forum.xojo.com/51746-dictionary-how-do-i-get-the-value. As the title of that post was a bit ambiguous I decided to make a new one for the benefit of future seekers.
As @Jeff Tullin pointed out in that thread, two-way, or “reverse-lookup” is problematic if keys and values are not unique, as the results will be ambiguous. Nonetheless, I find the functionality very useful in certain cases where the key:value pairs are well-defined beforehand and don’t contain any duplications. My particular use case at this time involves hardware whose parameters are controlled by integer values unrelated to the actual values they manifest, for example a programmable-gain amplifier whose gain might be 1, 10, 20, or 50, as determined by control values of 0,1,2,and 3. While there are other ways to do this (as always), I find It convenient and clean in my Xojo apps to be able to store these equivalencies in just one property where I can look up the real value from the control value and vice-versa. So FWIW here’s the code, which turns out to be rather trivial:
[code]Class DictionaryTwoWay
Sub Constructor(ParamArray Key_Values() As Pair)
LR = New Dictionary
RL = New Dictionary
For Each p As Pair In Key_Values
LR.Value(p.Left) = p.Right
RL.Value(p.Right) = p.Left
Next
End Sub
Function Value(Key As Variant) As Variant
If LR.HasKey(Key) Then
Return LR.Value(Key)
Elseif RL.HasKey(Key) Then
Return RL.Value(Key)
End
End Function
Sub Value(Key As Variant, assigns Val as Variant)
LR.Value(Key) = Val
RL.Value(Val) = Key
End Sub
Function HasKey(Key as Variant) as Boolean
If LR.HasKey(Key) Then Return True
If RL.HasKey(Key) Then Return True
End Function
Property
Private LR As Dictionary
EndProperty
Property
Private RL As Dictionary
EndProperty
End Class
[/code]
Usage is the same as a standard dictionary. It’s up to the developer to ensure uniqueness of keys and values, but if there are duplicates no exception is raised, it simply returns the value corresponding to the first key it finds. If it doesn’t find a key it returns nil, but there is a HasKey function just like the standard dictionary.