字典文字中是否可以有可选键?

是否可以在dict文字中包含“可选”键,而不是在if语句中添加它们?


像这样:


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",

}

编辑上下文:我知道如何执行逻辑:)我只是想避免使用if语句,因为我的对象是代表声明性逻辑的大数据块,因此移动内容有点像“意大利面条式编码”,不是意味着完全是程序性的。我希望对象的值“看起来像是什么意思”作为查询。


它实际上是一个Elasticsearch查询,因此它将如下所示:


{

    "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": [ ... ]

}

而我可能会怀疑的目标是使它看起来像一个查询,您可以查看它并了解它的形状,而不必通过ifs进行跟踪。即,没有“过滤器”:[f中的f为过滤器中的f,如果启用f。],因为然后您必须去寻找过滤器,无论如何,这些过滤器都是可选常数


翻过高山走不出你
浏览 160回答 3
3回答

蓝山帝景

正如其他答案所述,我认为答案是“否”,但这是我到目前为止获得的最接近的答案...虽然它稍微有点在“ wtf”的“令人讨厌”的一面a = Trueb = Falsec = Trued = Falseobj = {&nbsp; &nbsp; **({"do_a": "args for a"} if a else {}),&nbsp; &nbsp; **({"do_b": "args for b"} if b else {}),&nbsp; &nbsp; **({"do_c": "args for c"} if c else {}),&nbsp; &nbsp; **({"do_d": "args for d"} if d else {}),}#expect:assert(obj == {&nbsp; &nbsp; &nbsp; &nbsp; "do_a": "args for a",&nbsp; &nbsp; &nbsp; &nbsp; "do_c": "args for c",&nbsp; &nbsp; })或者,如果您想在某些函数中添加可选性,请执行以下操作:def maybe(dictionary, condition, default=None):&nbsp; &nbsp; return dictionary if condition else default or {}obj = {&nbsp; &nbsp; **maybe({"do_a": "args for a"}, a),&nbsp; &nbsp; **maybe({"do_b": "args for b"}, b),&nbsp; &nbsp; **maybe({"do_c": "args for c"}, c),&nbsp; &nbsp; **maybe({"do_d": "args for d"}, d),}这种代码的问题在于条件离结果越来越远(可以想象,我们最终将大字典传递给中的第一个参数maybe)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python