首页 > 解决方案 > 使用另一个字典键和值构造字典

问题描述

我有下面的字典。

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

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

    {
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "country.keyword": [
                  "Germany",
                  "France"
                ]
              }
            },
            {
              "terms": {
                "games.keyword": [
                  "Football",
                  "Motorsport"
                ]
              }
            },
            {
              "match": {
                "bayern.keyword": ["Muller"]
              }
            }
          ]
        }
      }
    }

if my_d = {'country': ['Germany',"France"]}or my_d = {'country': ['Germany',"France"], 'games': None, 'bayern':None}

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

标签: pythondictionary

解决方案


一般来说,我建议使用 Elasticsearch 3rd 方 python 包查询 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
        }
      }
    }

推荐阅读