Serj Serj - 2 years ago 201
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()}
if isinstance(q, list):
return [fix(i) for i in q]
return q

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download