I am building a dictionary from optional keyword arguments.
Currently I have code like this:
payload = {
"premium": kwargs.get("premium") or "",
"comments": kwargs.get("comments") or "",
"overridden": kwargs.get("overridden", False),
}
The problem is that using or "" also replaces valid falsy values.
For example:
kwargs = {
"premium": 0,
"comments": None,
"overridden": False,
}
I want the resulting dictionary to be:
{
"premium": 0,
"comments": "",
"overridden": False,
}
But:
kwargs.get("premium") or ""
returns "" when premium is 0.
I only want to replace the value when it is actually None, while preserving valid values such as:
0
False
""
I could write this for every field:
premium = kwargs.get("premium")
premium = "" if premium is None else premium
but I have many fields in the payload.
Is there a clean Pythonic way to handle this without treating every falsy value as missing?
Asked AI also and did not help at all.