I'd like to construct a dictionary, but only add the item if the value of the item is truthy
I do the following
my_dict = {
"key1": convert_value("foo"),
"key2": convert_value(None),
"key3": convert_value(""),
"key4": "bar",
"key5": ""
}
Problem is, I do not want the key to be in the dictionary at all, if its converted_value() is falsy, for example key2 and key3, which will both be empty strings after converting it with the convert_value() function.
the resulting dictionary, as is, would look like this
{
"key1": "foo",
"key2": "",
"key3": "",
"key4": "bar",
"key5": ""
}
however I'd like the resulting dict to be just this
{
"key1": "foo",
"key4": "bar",
"key5": "",
}
without the keys2 and 3 which returned empty values after conversion. Is there any way to do this in-line - during the construction directly?
I cannot use dict comprehension because not all the values go through the convert_value function before getting added (those keys can have empty values), and removing them in hindsight seems wasteful
EDIT: What I'm really looking for is similar to providing a default value as follows
"key2": convert_value("foo") or pass,
ie: skip this key entirely. That would be perfect.