0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can just use more A if C else B

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.