I need to create a data payload for a restful web api. The template for the dict contains some optional keys. The usual way is to create a dict with all the required keys and then check and add optional keys one by one:
def create_payload(key1, key2, ..., key10=None,key11=None):
data = {
'key1' : key1,
'key2' : key2,
...
'nested' : {}
}
if key10:
data[ 'nested' ][ 'key10' ] = key10
if key11:
data[ 'key11' ] = key11
return data
Is there an alternative way to start with the data template and then automatically delete optional keys that are None?
def create_payload(key1, key2, ..., key10=None,key11=None):
data = {
'key1' : key1,
'key2' : key2,
...
'nested' : {
'key10' : key10
},
'key11' : key11
}
# delete keys that are None
return data
UPDATE Some of you suggested doing dictionary comprehension to remove None keys:
{k: v for k, v in metadata.items() if v is not None}
In my attempt to create a simple example, I didn't account for the possibility that some of the keys may be nested. (I am updating the example above.) Is there a dictionary comprehension that can exclude None values inside nested keys?