python - 在特定深度的 dict 上添加项目
问题描述
我正在使用 Elasticsearch,我需要构建一个类似 JSON 的 dict 对象来查询复杂的聚合。
每个聚合都具有以下格式:
{
"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中实现这个数据结构,第二段代码呢?为每个聚合项放入一个新叶子。
谢谢
解决方案
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'}}}}]
推荐阅读
- blockchain - 区块链是否包含 websocket 服务器?
- javascript - React Context API 并避免重新渲染
- java - 我正在尝试查看一个较小的字符串是否包含在另一个较大的字符串中,并且我想拆分该字符串
- python - 无法运行 Spyder,因为没有名为“PySide”的模块
- r - 如何将 h2o 系数表转换为 R 中的模型对象
- flutter - flutter, PageRouteBuilder, 添加水平过渡
- javascript - 基于具有多个实例的同一类上的突变触发jquery
- ruby - 使用 Watir 设置复选框
- r - 数据帧头中的百分比符号
- linux - 用于 grep 选择日期范围的 unix 脚本?