[英]Add item on dict at specific depth
我正在使用 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'}}}}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.