Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard in dictionary key

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)
like image 546
gwydion93 Avatar asked Oct 05 '18 00:10

gwydion93


People also ask

What is the wildcard character in Python?

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

How do I find a dictionary key?

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


2 Answers

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.

like image 174
falsetru Avatar answered Sep 28 '22 08:09

falsetru


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
like image 21
jpp Avatar answered Sep 28 '22 08:09

jpp