我是python的新手,并且在下面的python代码中想知道如何有条件地添加变量。
requestBody = json.dumps({"accountId":accountId,
"emailSubject":customData.emailSubject,
"emailBlurb":customData.emailBlurb,
"customFields":customFields,
"status":customData.status,
"messageLock":customData.messageLock})
例如,我希望"custom"Fields:customFields
仅包括在内,如果它不是null,则不包括。如何做到这一点?
答案 0 :(得分: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)
答案 1 :(得分: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)