Wildcard in dictionary key

微笑、不失礼 提交于 2019-12-07 10:54:17

问题


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)

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/52656701/wildcard-in-dictionary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!