【问题标题】:Beautify the Python Nested Dictionary Code美化 Python 嵌套字典代码
【发布时间】:2020-09-14 05:16:09
【问题描述】:

输出:

{
  "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 个字典,但我不喜欢我们访问键和添加键值的方式对。

【问题讨论】:

  • 不清楚您的要求。 json.dumps 支持许多功能,如缩进、排序键等。查看documentation,然后相应地编辑您的问题。来自review
  • 不,该行现在被注释掉了。

标签: python json python-3.x elasticsearch elasticsearch-aggregation


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多