Someone recently gave me the task to figure out how to reverse a dictionary. Basically they wanted to switch the keys and values so the values become the keys and the keys become the values. Instead of trying to figure it out myself, I googled reverse dictionary and found it on stackoverflow. You simply say
var newDictionary = oldDictionary.ToDictionary(x => x.Value, x => x.Key);
if you think you may have duplicates then use:
var newDictionary = oldDictionary.GroupBy(pair => pair.Value).Select(group => group.First()).ToDictionary(pair => pair.Value, pair => pair.Key);
If you just want to search values linearly to find a key using the value(for smaller dictionaries) use:
var result = (from val in oldDictionary.Keys where valToFind == oldDictionary[val] select val).First();
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

sender rPosted Mar 23, 2014, 3:38 AM
Do you have java code to implement reverse dictionary?