Python,使用通配符访问字典
我有一本包含项的字典,其中的键是某种正则表达式.我正在寻找一个只要传递匹配字符串就返回匹配项列表的函数
I have a dictionary with items, where the keys are some kind of regular expressions. I am looking for a function to return a list of matching items whenever a matching string is passed
d = {'a.b': item1, 'b.c':item2}
func(d,'a1b')
>>> [item1]
func(d,'b2c')
>>> [item2]
有没有一种pythonic的方法来做到这一点?我唯一能想到的解决方案是:
Is there a pythonic way to do this ? The only solution I can come up with is:
import re
def func(d, event):
res = list()
for key, item in d.iteritems():
if re.match(key, event):
res.append(item)
return res
您可以创建一个包装字典类的类,该类将为您完成:
You can create a class that will do that for you that wraps the dictionary class:
import re
class RegexDict(dict):
def get_matching(self, event):
return (self[key] for key in self if re.match(key, event))
使用示例:
>>> d = {'a.b': 'item1', 'b.c': 'item2'}
>>> rd = RegexDict(d)
>>> for o in rd.get_matching('a1b'):
print o
item1
这省去了依赖外部功能的麻烦,使开销较小,并且更健壮.
This saves you having to rely on external functions, it keeps the overhead small, and is more robust.
您还可以添加另一个函数,该函数将列表(或iter)作为输入并返回所有匹配的值:
You could also add another function that takes a list (or iter) as input and returns all matching values:
def get_all_matching(self, events):
return (match for event in events for match in self.get_matching(event))
>>> for o in rd.get_all_matching(['a1b', 'b2c']):
print o
item1
item2