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)
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.