Can we filter a hinner list?
tarzasai opened this issue · comments
Giorgio Gelardi commented
I'm trying to filter a list inside a dict:
import pycond as pc
data = {
'x': [
{'a': 1},
{'a': 2}
]
}
expr = '[x.a eq 2]'
filtered = list(filter(pc.make_filter(expr), data))
print('matching:', filtered)
I was hoping to use the prefix without an actual index (like Elasticsearch) but I get an AttributeError.
Is it even possible?
Gunther Klessinger commented
if you want exactly your syntax you need a custom value lookup function AND overload the eq function:
def test_any_in_list(s):
# https://github.com/axiros/pycond/issues/3
def foo(a, b):
# if a is a set, then check for containment:
return b in a if isinstance(a, set) else a == b
eq = pc.OPS['eq']
pc.OPS['eq'] = foo
def lu(k, v, state):
for part in k.split('.'):
if isinstance(state, list):
state = set({i.get(part) for i in state})
else:
state = state.get(part)
return state, v
data = {'x': [{'a': 1}, {'a': 2}]}
expr = 'x.a eq 2'
f = pc.make_filter(expr, lookup=lu)
filtered = list(filter(f, [data]))
assert filtered == [{'x': [{'a': 1}, {'a': 2}]}]
Gunther Klessinger commented
Closing it; If not content pls. re-open.