Serj Serj - 6 months ago 23
Python Question

Recursive lambda in Python

I have a structure like this:

{"query": {"or": ["ids": [1,2,3], "text": "some text"]}}


The structure may vary, but the idea is to exclude the value corresponding to "ids" key.

I wrote a spike, but for some reason it doesn't work as expected, maybe a bug in Python? Or what's more probable it's my mistake:

fix = lambda q: {True: {k: '...' if k == 'ids' else fix(v) for k, v in q.items()}, False: {True: [fix(i) for i in q], False: q}[isinstance(q, list)]}[isinstance(q, dict)]


Here is a multiline analogy. It works as expected:

def fix(q):
if isinstance(q, dict):
return {k: ('...' if k == 'ids' else fix(v)) for k, v in q.items()}
else:
if isinstance(q, list):
return [fix(i) for i in q]
else:
return q

Answer

Hint: You need {True: lambda: A, False: lambda: B}[condition]() to selectively evaluate expressions, or else both branches are evaluated anyways and it might cause errors.