美化Python嵌套字典代码

2024-10-02 14:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

输出:

{
  "aggs": {
    "overall": {
      "date_histogram": {
        "field": "created",
        "calendar_interval": "day",
        "time_zone": 3
      },
      "aggs": {
        "series_attribute": {
          "terms": {
            "field": 2
          },
          "aggs": {
            "types_count": {
              "value_count": {
                "field": 1
              }
            }
          }
        }
      }
    }
  }
}

输入: 聚合1=

{
                "types_count": {
                            "value_count": {
                                "field": 1
                            }
                        }
            }

聚合2=

{
            "series_attribute": {
                "terms": {
                    "field": 2
                }
            }
        }

聚合3=

{
            "overall": {
                "date_histogram": {
                    "field": "created",
                    "calendar_interval": "day",
                    "time_zone": 3
                }
            }
        }



countResponse,termResponse,dateResponse = {},{},{}
countResponse["aggs"] = aggregation1
termResponse["aggs"] = aggregation2
dateResponse["aggs"] = aggregation3
aggregation2["series_attribute"]["aggs"] = aggregation1
aggregation3["overall"]["aggs"] = termResponse["aggs"]
#print(json.dumps(dateResponse))

这段代码可以工作,但我不确定是否可以修改代码使其看起来更好。我在另一个字典中嵌套了3个字典,但我不喜欢我们访问键和添加键值对的方式


Tags: fielddatetimecountattributecalendarserieshistogram
2条回答

假设您需要分配countResponse、termResponse、dateResponse变量, 你可以这样做:

dateResponse = {"aggs":aggregation3}
aggregation2["series_attribute"] = countResponse = {"aggs":aggregation1}
aggregation3["overall"] = termResponse = {"aggs":aggregation2}

您可以这样更改代码以使其更具可读性

output = { "aggs" : aggregation3 }
aggregation3["overall"]["aggs"] = aggregation2
aggregation2["series_attribute"]["aggs"] = aggregation1

相关问题 更多 >