Is it possible to have optional keys in a dict literal?

  • A+

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 ifs. 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


Start by defining your lists of keys, arguments, and boolean variables:

keys = ["do_a", "do_b", ...] args = ["args for a", "args for b", ...] mask = [a, b, ...] 

Now, construct obj using the mask list to determine what keys are inserted:

obj = {k : a for k, a, m in zip(keys, args, mask) if m} 


obj = {} for k, a, m in zip(keys, args, mask):     if m:         obj[k] = a 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: