Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "like" on dictionary key?

Tags:

c#

.net

linq

How can I do a "like" to find a dictionary key? I'm currently doing:

mydict.ContainsKey(keyName);

But some keyNames have an additional word appended (separated by a space), I'd like to do a "like" or .StartsWith(). The comparisons will look like this:

"key1" == "key1"  //match
"key1" == "key1 someword" //partial match

I need to match in both cases.

like image 945
4thSpace Avatar asked Jan 25 '12 18:01

4thSpace


People also ask

Can you set a dictionary key?

Is it safe to use a frozenset as a dict key? Yes. According to the docs, Frozenset is hashable because it's immutable. This would imply that it can be used as the key to a dict, because the prerequisite for a key is that it is hashable.

How do I get the key of a dictionary in a string?

Use str() and dict. items() to convert dictionary keys and values to strings. Call dictionary.

Can I use list as key in dictionary Python?

A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.

What is the code to list the keys of a dictionary D?

The dict. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.


2 Answers

You can use LINQ to do this.

Here are two examples:

bool anyStartsWith = mydict.Keys.Any(k => k.StartsWith("key1"))

bool anyContains = mydict.Keys.Any(k => k.Contains("key1"))

It is worth pointing out that this method will have worse performance than the .ContainsKey method, but depending on your needs, the performance hit will not be noticable.

like image 200
Kevin McCormick Avatar answered Sep 28 '22 06:09

Kevin McCormick


mydict.Keys.Any(k => k.StartsWith("key1"));

While enumerating over the Keys you will lose the performance benefits of a dictionary:

mydict.ContainsKey(someKey); // O(1)
mydict.Keys.Any(k => k.StartsWith("key1")); // O(n)
like image 20
Stefan Avatar answered Sep 28 '22 06:09

Stefan