0

我是 python 新手,想知道在下面的 python 代码中如何有条件地添加变量。

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

例如,如果它不为空,我只想"custom"Fields:customFields被包括在内。如何做到这一点?

4

2 回答 2

2

创建一个字典,然后向其中添加键,然后转储它。这种通用的处理方式允许您对每个键使用不同的逻辑(例如,如果给定的键是> 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)
于 2013-08-08T09:22:32.680 回答
2

使用 dict 理解:

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})

单线展开:

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)
于 2013-08-08T09:23:13.550 回答