Suppose I have a dictionary:
rank_dict = {'V*': 1, 'A*': 2, 'V': 3,'A': 4}
As you can see, I have added a * to the end of one V. Whereas a 3 may be the value for just V, I want another key for V1, V2, V2234432, etc...I want to check it against:
checker = 'V30'
and get the value. what is the correct syntax for this?
for k, v in rank_dict.items():
if checker == k:
print(v)
The asterisk ( ∗) An asterisk ∗ is used to specify any number of characters. It is typically used at the end of a root word. This is great when you want to search for variable endings of a root word. For example, searching for work* would tell the database to look for all possible word-endings to the root “work”.
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().
You can use fnmatch.fnmatch
to match Unix shell-style wildcards:
>>> import fnmatch
>>> fnmatch.fnmatch('V34', 'V*')
True
>>> rank_dict = {'V*': 1, 'A*': 2, 'V': 3,'A': 4}
>>> checker = 'V30'
>>> for k, v in rank_dict.items():
... if fnmatch.fnmatch(checker, k):
... print(v)
...
1
NOTE: Every lookup will have O(n) time complexity. This may become an issue with large dictionaries. Recommended only if lookup performance is not an issue.
I would split your single dictionary into two, a regular one and a wildcard-derived one, so you can maintain O(1) lookup time complexity.
rank_dict = {'V*': 1, 'A*': 2, 'V': 3,'A': 4}
d1 = {k: v for k, v in rank_dict.items() if not k.endswith('*')}
d2 = {k[0]: v for k, v in rank_dict.items() if k.endswith('*')}
def get_val(key, d1, d2):
return d1.get(key, d2.get(key[0]))
get_val('V', d1, d2) # 3
get_val('V30', d1, d2) # 1
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