How can one check if a key/value pair exists in a Dictionary<>? I'm able to check if a key or value exist, using ContainsKey
and ContainsValue
, but I'm unsure of how to check if a key/value pair exist.
Thanks
How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
Use any() & List comprehension to check if a value exists in a list of dictionaries.
Well the pair can't exist if the key doesn't exist... so fetch the value associated with the key, and check whether that's the value you were looking for. So for example:
// Could be generic of course, but let's keep things simple... public bool ContainsKeyValue(Dictionary<string, int> dictionary, string expectedKey, int expectedValue) { int actualValue; if (!dictionary.TryGetValue(expectedKey, out actualValue)) { return false; } return actualValue == expectedValue; }
Or slightly more "cleverly" (usually something to avoid...):
public bool ContainsKeyValue(Dictionary<string, int> dictionary, string expectedKey, int expectedValue) { int actualValue; return dictionary.TryGetValue(expectedKey, out actualValue) && actualValue == expectedValue; }
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