Be very careful when changing the key / value relationship in the dictionary.
The dictionary contract ensures that for each value in the collection there is exactly one key that maps to this value. The keys are unique. But the converse is not true; for each individual value there can be many different keys matching this value.
In my own personal code library (written in Java, which is pretty close), I have a MultiMap class for this kind of thing. Although keys are unique, each key can be associated with multiple values. It is exactly identical to Map>.
When I need to search for keywords in a collection, I do something like this:
Map<K, V> lookupTable = ...; MultiMap<V, K> reverseLookupTable = MapUtil.invert(lookupTable); V value = ...; if (reverseLookupTable.containsKey(value)) { Set<K> keys = reverseLookupTable.get(value); }
If you use something other than MultiMap (like HashMap or Dictionary) as your reverse lookup table, you risk losing some of your V-> K mappings, unless you can guarantee that all keys and all values ββin your collection are unique.
EDIT:
Unfortunately. I just noticed that you said that all the keys and values ββin your collection are unique. But I will leave my answer here in any case, as a warning to others reading this who may not be able to provide the same guarantee.
benjismith
source share