将类似sql的查询映射到python中的筛选词典列表
我有一个字典列表,我想对其应用“类似SQL”的筛选查询 用户提供的字符串可以如下所示: “type1==Hello&&type2=~World”-和运算符 “type1==你好| | type2=~世界”-或操作员 我设法过滤了一个参数,例如“type1==Hello”,而没有使用&&/| | 基本上,我正在努力使用&&| | |(和/或运算符)将“类似SQL”的格式映射到字典列表上的真正过滤器 如果有人能帮我,那就太好了将类似sql的查询映射到python中的筛选词典列表,python,list,dictionary,Python,List,Dictionary,我有一个字典列表,我想对其应用“类似SQL”的筛选查询 用户提供的字符串可以如下所示: “type1==Hello&&type2=~World”-和运算符 “type1==你好| | type2=~世界”-或操作员 我设法过滤了一个参数,例如“type1==Hello”,而没有使用&&/| | 基本上,我正在努力使用&&| | |(和/或运算符)将“类似SQL”的格式映射到字典列表上的真正过滤器 如果有人能帮我,那就太好了 def filter_host(hosts, filter_str, c
def filter_host(hosts, filter_str, categories):
def not_contains(a, b):
return b not in a
def and_(a, b):
return a and b
def or_(a, b):
return a or b
ops = {
"==": operator.eq,
"<": operator.lt,
">": operator.gt,
"!=": operator.ne,
'=~': operator.contains,
'!~': not_contains,
'&&': and_,
'||': or_
}
try:
key, op, value = re.match(r'(\w+)\s*(>|<|(?<!=)~=(?!=)|(?<!=)==(?!=)|(?<!=)>(?!=)|(?<!=)!~(?!=)|(?<!=)!=(?!=))\s*(\w*.*|\d*.*)',
filter_str).groups()
if key in categories:
if _keys_mapping.get(key).get('type') == 'float':
value = float(value)
elif _keys_mapping.get(key).get('type') == 'int':
value = int(value)
operator_func = ops[op]
filtered_hosts = list(filter(lambda host: operator_func(host.get(_keys_mapping[key]['name']), value), hosts))
if filtered_hosts:
return filtered_hosts
else:
raise Exception('No matching values')
else:
raise Exception('Key not exist. Allowed keys for this query are: ' + ', '.join(categories))
except ValueError:
handle_exceptions('Filter option not implanted')
except AttributeError:
handle_exceptions('Filter option not implanted')
def filter\u主机(主机、筛选器、类别):
def不包含(a,b):
返回b不在a中
定义和定义(a,b):
返回a和b
定义或定义(a,b):
返回a或b
ops={
“=”:operator.eq,
“”:operator.gt,
“!=”:operator.ne,
“=~”:运算符.contains,
“!~”:不包含,
“&&”:和,
“| |”:或_
}
尝试:
键,op,value=re.match(r'(\w+)\s*(>|