python - 在特定深度的字典上添加项目

标签 python list dictionary elasticsearch recursion

我正在与Elasticsearch一起使用,我需要构建一个类似于JSON的字典对象以查询复杂的聚集。

每个聚集都具有以下格式:

{
"aggs": {
    "agg_by_field_1": {
        "terms": {
            "script": {
                "source": "whatever"
                }
            }
         }
    }
}

但是,每个聚合也都有下一个聚合的叶子:
{
"aggs": {
    "agg_by_field_1": {
        "terms": {
            "script": {
                "source": "whatever"
            }
        },
        "aggs": {
            "agg_by_field_2": {
                "terms": {
                    "script": {
                        "source": "whatever_2"
                        }
                    }
                 }
            }
         }
    }
}

现在,我对每个聚合都有一个简单的list:
[
    {
        "agg_by_field_1": {
            "terms": {
                "script": {
                    "source": "whatever"
                }
            }
        }
    },
    {
        "agg_by_field_2": {
            "terms": {
                "script": {
                    "source": "whatever_2"
                }
            }
        }
    },
]

那么,如何在python中实现此数据结构,第二段代码?在dict中为每个聚合项添加新的叶子。

谢谢

最佳答案

Python开箱即用地支持这种结构。这称为嵌套Dictionary。您可以在这里阅读更多有关此的信息:https://www.programiz.com/python-programming/nested-dictionary

实际上,您的代码无需更改即可直接工作:

>>> d = {
... "aggs": {
...     "agg_by_field_1": {
...         "terms": {
...             "script": {
...                 "source": "whatever"
...             }
...         },
...         "aggs": {
...             "agg_by_field_2": {
...                 "terms": {
...                     "script": {
...                         "source": "whatever_2"
...                         }
...                     }
...                  }
...             }
...          }
...     }
... }
>>> d
{'aggs': {'agg_by_field_1': {'terms': {'script': {'source': 'whatever'}}, 'aggs': {'agg_by_field_2': {'terms': {'script': {'source': 'whatever_2'}}}}}}}

>>> d = [
    {
        "agg_by_field_1": {
            "terms": {
                "script": {
                    "source": "whatever"
                }
            }
        }
    },
    {
        "agg_by_field_2": {
            "terms": {
                "script": {
                    "source": "whatever_2"
                }
            }
        }
    },
]
>>> d
[{'agg_by_field_1': {'terms': {'script': {'source': 'whatever'}}}}, {'agg_by_field_2': {'terms': {'script': {'source': 'whatever_2'}}}}]

关于python - 在特定深度的字典上添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59738479/

相关文章:

python - 尝试为动态添加的类覆盖 __getattr__ 但仅能正常工作

python - 如何使用 python 在 Windows 7 中制作屏幕截图?

python - 将python路径放在windows机器上

c++ - 将新节点添加到列表并动态命名它

linux - 如何获得 shell 脚本中的函数列表?

python - 如何将多个字典中的数据合并到 DataFrame 中的一行中

ios - 如果另一个模型中存在值,则更新模型的属性

Python Multiprocessing - 修改共享字典中的值

python - 如何使用 python 脚本从一台远程服务器连接到另一台远程服务器?

list - 在 Prolog 中打乱列表