美化 Python 嵌套字典代码

Beautify the Python Nested Dictionary Code

输出:

{
  "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))

此代码有效,但我不确定是否可以修改代码以使其看起来 better.I 已将 3 个字典一个嵌套在另一个字典中,但我不喜欢我们访问键和添加的方式键值对。

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

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

假设您需要分配 countResponse,term Response,data Response 变量, 你可以这样做:

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