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.
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.
Use str() and dict. items() to convert dictionary keys and values to strings. Call dictionary.
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.
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.
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.
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)
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