I would like to know if some property or method exists that gets the index of a specific value.
I found that dictionaries have the Contains()
method which returns true if the value passed in exists, so this method almost implements what I need.
I know that I can loop through all the value pairs and check the condition, but I ask because maybe there's an optimized way of doing this.
Use the list[index] function to get index numbers from the dictionary. It will return the key and also use the items() function to return a collection from a dictionary.
+1 For OrderedDictionary , since Dictionary does not have indices.
You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary.
There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).
Obviously you can get the key from a KeyValuePair
just by using the Key
property, so that will let you use the indexer of the dictionary:
var pair = ...; var value = dictionary[pair.Key]; Assert.AreEqual(value, pair.Value);
You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:
var key = dictionary.Where(pair => pair.Value == desiredValue) .Select(pair => pair.Key) .FirstOrDefault();
key
will be null if the entry doesn't exist.
This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.
Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.
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