Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dictionary key by value

Tags:

c#

dictionary

How do I get a Dictionary key by value in C#?

Dictionary<string, string> types = new Dictionary<string, string>() {     {"1", "one"},     {"2", "two"},     {"3", "three"} }; 

I want something like this:

getByValueKey(string value); 

getByValueKey("one") must be return "1".

What is the best way do this? Maybe HashTable or SortedLists?

like image 341
loviji Avatar asked Mar 14 '10 22:03

loviji


People also ask

Can you get the key of a dictionary with value?

We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.

Can you get the key of a dictionary by value Python?

A Python dictionary is a collection of key-value pairs, where each key has an associated value. Use square brackets or get() method to access a value by its key. Use the del statement to remove a key-value pair by the key from the dictionary. Use for loop to iterate over keys, values, key-value pairs in a dictionary.

How do I find a specific key in a dictionary?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

How do you get a specific value from a dictionary in Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.


2 Answers

Values do not necessarily have to be unique, so you have to do a lookup. You can do something like this:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key; 

If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.

like image 76
Kimi Avatar answered Oct 06 '22 03:10

Kimi


You could do that:

  1. By looping through all the KeyValuePair<TKey, TValue>'s in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary)
  2. Use two dictionaries, one for value-to-key mapping and one for key-to-value mapping (which would take up twice as much space in memory).

Use Method 1 if performance is not a consideration, and use Method 2 if memory is not a consideration.

Also, all keys must be unique, but the values are not required to be unique. You may have more than one key with the specified value.

like image 41
Zach Johnson Avatar answered Oct 06 '22 04:10

Zach Johnson