Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lookup / check a dictionary value by key

Tags:

c#

.net

windows

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

like image 327
user1559618 Avatar asked Jul 29 '12 12:07

user1559618


People also ask

How do you check if a dictionary has a specific key?

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.

Can we search in values of dictionary Python?

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.


2 Answers

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
}
like image 87
Zbigniew Avatar answered Oct 04 '22 14:10

Zbigniew


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");
like image 45
M. Mennan Kara Avatar answered Oct 04 '22 14:10

M. Mennan Kara