Search code examples
pythonjsonpython-3.xelasticsearchelasticsearch-aggregation

Beautify the Python Nested Dictionary Code


Output :

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

Input : aggregation1 =

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

aggregation2 =

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

aggregation3 =

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

This code works but I am not sure if the code can be modified to look better.I have nested 3 dictionaries one inside the another but I do not like the way in which we are accessing the keys and adding the key-value pair.


Solution

  • You can change the code like so to make it more readable.

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