1

I am new to python and was wondering in the below python code how to add a variable conditionally.

requestBody = json.dumps({"accountId":accountId,
        "emailSubject":customData.emailSubject,
        "emailBlurb":customData.emailBlurb,
        "customFields":customFields,
        "status":customData.status,
        "messageLock":customData.messageLock})

Like for example i want "custom"Fields:customFields only to be included if its not null else not.How to do this??

2 Answers 2

3

Create a dictionary and then add keys to it, then dump it. This general way of doing things allows you to use different logic for each key (e.g. if a given key is > 10).

to_json = {"accountId":accountId,
    "emailSubject":customData.emailSubject,
    "emailBlurb":customData.emailBlurb,
    "customFields":customFields,
    "status":customData.status,
    "messageLock":customData.messageLock}

if james is not None:
  to_json['james'] = james

requestBody = json.dumps(to_json)
Sign up to request clarification or add additional context in comments.

Comments

2

Using dict comprehension:

requestBody = json.dumps({key: value for key, value in [
        ("accountId",accountId),
        ("emailSubject",customData.emailSubject),
        ("emailBlurb",customData.emailBlurb),
        ("customFields",customFields),
        ("status",customData.status),
        ("messageLock",customData.messageLock),] if value is not None})

One-liner expanded:

pairs = [
    ("accountId", accountId),
    ("emailSubject", customData.emailSubject),
    ("emailBlurb", customData.emailBlurb),
    ("customFields", customFields),
    ("status", customData.status),
    ("messageLock", customData.messageLock),
]:

d = {}
for key, value in pairs:
    if value is not None:
        d[key] = value

requestBody = json.dumps(d)

1 Comment

What if the value is 0? Obviously check with is None but when being clever you should always be sufficiently clever otherwise you risk one-liners with bugs.

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.