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?
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.
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.
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.
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.
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.
You could do that:
KeyValuePair<TKey, TValue>
's in the dictionary (which will be a sizable performance hit if you have a number of entries in the dictionary)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With