Is it possible to have 'optional' keys in a dict literal, rather than add them in in if
statements?
Like so:
a = True
b = False
c = True
d = False
obj = {
"do_a": "args for a" if a,
"do_b": "args for b" if b,
"do_c": "args for c" if c,
"do_d": "args for d" if d,
}
#expect:
obj == {
"do_a": "args for a",
"do_c": "args for c",
}
Edit for context:
I know how to do the logic :) I just want to avoid if
statements because my object is a big block of data that represents declarative logic, so moving stuff around is a bit like "spaghetti coding" something that isn't meant to be procedural at all.
I want the value of the object to "look like what it means" as a query.
It's actually an elasticsearch query, so it will look like this:
{
"query": {
"bool": {
"must": [
<FILTER A>,
<FILTER B>, # would like to make this filter optional
<FILTER C>,
{
"more nested stuff" : [ ... ]
}
],
"other options": [ ... ]
},
"other options": [ ... ]
},
"other options": [ ... ]
}
and my possibly-dubious goal was to make it look like a query that you could look at and understand the shape of it, without having to trace through if
s.
ie, without having "filters": [f for f in filters if f.enabled]
because then you have to go and look for the filters, which are all optional-constants anyway here