I am trying to confirm whether a specific dictionary key contains a value
e.g.
does dict01 contain the phrase "testing" in the "tester" key
At the moment I am having to iterate through the dictionary using KeyPair, which I don't want to have to do as it wasting performance
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
In this Program, we will discuss how to find the value by key in Python dictionary. By using the dict. get() function, we can easily get the value by given key from the dictionary. This method will check the condition if the key is not found then it will return none value and if it is given then it specified the value.
You can use ContainsKey and string.Contains:
var key = "tester";
var val = "testing";
if(myDictionary.ContainsKey(key) && myDictionary[key].Contains(val))
{
// "tester" key exists and contains "testing" value
}
You can also use TryGetValue:
var key = "tester";
var val = "testing";
var dicVal = string.Empty;
if(myDictionary.TryGetValue(key, out dicVal) && dicVal.contains(val))
{
// "tester" key exists and contains "testing" value
}
You can use the following method if you don't want to iterate through the dictionary twice
string value;
var result = dict01.TryGetValue("tester", out value) && value.Contains("testing");
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