Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do a dictionary reverse lookup

Tags:

c#

I have a dictionary of type <string, string> and for a particular case, I need to do a reverse lookup. So for instance suppose I have this entry <"SomeString", "ab"> and that I pass in "ab" then I would like to return "SomeString". Before I embark on a foreach loop over every entry in the dictionary, I was wondering what would be the most efficient way to do this reverse lookup?

like image 405
frenchie Avatar asked Mar 23 '14 19:03

frenchie


People also ask

What is reverse lookup in dictionary?

A reverse dictionary lookup will return a list containing all the keys in a dictionary. Dictionary keys map values and are used to access values in dictionaries. dictionary = {'a': 1, 'b': 2, 'c': 3} lookup_val = 1 all_keys = [] for key, value in dictionary. items(): if(value == lookup_val): all_keys.

Can I reverse dictionary python?

Instead of using a for loop, we can reverse a dictionary in a single python statement using dictionary comprehension. Here, we will create the output dictionary by reversing the key and value in each key-value pair of the dictionary as follows.

How do you reverse a dictionary in C#?

1. Using foreach loop. The idea is to create a new instance of Dictionary<TValue,TKey> for a given dictionary of type Dictionary<TKey,TValue> . Then use a foreach loop to iterate over the dictionary, and insert each mapping into the new Dictionary in reverse order of its key-value pair.


2 Answers

Basically, You can use LINQ and get the Key like this, without reversing anything:

var key = dictionary.FirstOrDefault(x => x.Value == "ab").Key; 

If you really want to reverse your Dictionary, you can use an extension method like this:

public static Dictionary<TValue, TKey> Reverse<TKey, TValue>(this IDictionary<TKey, TValue> source) {      var dictionary = new Dictionary<TValue, TKey>();      foreach (var entry in source)      {          if(!dictionary.ContainsKey(entry.Value))              dictionary.Add(entry.Value, entry.Key);      }      return dictionary; }  

Then you can use it like this:

var reversedDictionary = dictionary.Reverse(); var key = reversedDictionary["ab"]; 

Note: if you have duplicate values then this method will add the first Value and ignore the others.

like image 85
Selman Genç Avatar answered Sep 23 '22 18:09

Selman Genç


Use the Linq ToDictionary function:

var reversed = d.ToDictionary(x => x.Value, x => x.Key); 

You can see below that it works, as tested in Linqpad:

var d = new Dictionary<int, string>(); d.Add(1,"one"); d.Add(2,"two"); d.Dump(); //prints it out in linq-pad var reversed = d.ToDictionary(x => x.Value, x => x.Key); reversed.Dump(); //prints it out in linq-pad 

Prints

like image 34
Ismail Hawayel Avatar answered Sep 24 '22 18:09

Ismail Hawayel