Wildcard in dictionary 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) # 3get_val('V30', d1, d2) # 1