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

时间:2020-10-15 17:13:34

标签: python dictionary

我下面有字典。

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

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

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

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

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

1 个答案:

答案 0 :(得分:2)

通常,我建议使用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
        }
      }
    }