使用另一个字典键和值构造字典

2024-05-05 05:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面有一本字典

 my_d =    {'country': ['Germany',"France"],
     'games': ['Football,Motorsport'],
     'bayern': ['Muller']}

我需要使用上面的键和值创建一个字典

  • 每个键都将添加到输出keyword{}
    {
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "country.keyword": [
                  "Germany",
                  "France"
                ]
              }
            },
            {
              "terms": {
                "games.keyword": [
                  "Football",
                  "Motorsport"
                ]
              }
            },
            {
              "match": {
                "bayern.keyword": ["Muller"]
              }
            }
          ]
        }
      }
    }

如果{}或my_d={'country':['Germany','France'], “游戏”:无, “拜仁”:无}

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "country.keyword": [
              "Germany",
              "France"
            ]
          }
        }
      ]
    }
  }
}

1条回答
网友
1楼 · 发布于 2024-05-05 05:52:35

一般来说,我建议使用Elasticsearch第三方python包do query Elasticsearch,但我相信这段代码应该可以工作(python 3.5+):

must_clauses = [{f"{key}.keyword": value} for key, value in my_d.items()]
terms = [{"terms": must_clause} for must_clause in must_clauses]
query_template = {
      "query": {
        "bool": {
          "must": 
            terms
        }
      }
    }

相关问题 更多 >