python - 使用另一个字典键和值构造字典
问题描述
我有下面的字典。
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"]
}
}
]
}
}
}
if my_d = {'country': ['Germany',"France"]}
or my_d = {'country': ['Germany',"France"], 'games': None, 'bayern':None}
{
"query": {
"bool": {
"must": [
{
"terms": {
"country.keyword": [
"Germany",
"France"
]
}
}
]
}
}
}
解决方案
一般来说,我建议使用 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
}
}
}
推荐阅读
- excel - 我正在尝试更改多个工作簿的事件过程?
- azure - 将数据写入 Azure Data Lake Store - Powershell 脚本
- css - CSS改变反应MUI选择
- algorithm - 树证书中的子序列是否保证它包含给定的树?
- c# - 无法使用具有应用程序权限的 Microsoft Graph 获取用户信息
- c - 即使条件为假,while循环也会继续运行
- asp.net-core - NetCore 3.1 PostAsync CustomHeaders 不工作
- reactjs - 没有找到匹配的文件...。(反应JS)
- mysql - 如何远程或通过 IP 地址连接到 mariaDB?
- python - 多个字符串输入 - Python