1

I have the following JSON object and I need to replace all None values with 0 (zero) within parameters keys.

{
  "parameters": {
    "x_pos": 0,
    "y_pos": None,
    "x_pos": 0,
    "...": None,
  },
}

I'm wondering if this can be done in a Pythonic way? And what that way is called (for example, List Comprehension). I think it might look something like this:

params = j_obj.get('parameters')
for param in params:
  params[param] = params.get(param) if params.get(param) is not None else 0

1 Answer 1

1

You can use a dictionary comprehension:

j_obj['parameters'] = {a:0 if b is None else b for a, b in j_obj['parameters'].items()}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! is there any place I can study more about this kind of solution? For example, know all kinds of "comprehension" in python. You just taught me dictionary comprehension which I had no idea it existed, thank you for this!
@meetnick This is a good summary of both list and dictionary comprehensions. For reference, here is the official PEP on dictionary comprehension.
@meetnick Glad to help!

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.