【问题标题】:Line wrapping code for nested dictionaries in pythonpython中嵌套字典的换行代码
【发布时间】:2018-09-07 17:16:48
【问题描述】:

使用 Alexa 中的新 Entity Resolution,嵌套字典变得非常嵌套。引用深度嵌套值的最 Pythonic 方式是什么?如何编写代码保持在每行 79 个字符以内?

这是我目前拥有的,虽然它有效,但我很确定有更好的方法:

if 'VolumeQuantity' in intent['slots']:
    if 'resolutions' in intent['slots']['VolumeQuantity']:
        half_decibels = intent['slots']['VolumeQuantity']['resolutions']['resolutionsPerAuthority'][0]['values'][0]['value']['name'].strip()
    elif 'value' in intent['slots']['VolumeQuantity']:
        half_decibels = intent['slots']['VolumeQuantity']['value'].strip()

这是来自 alexa 的部分 json 示例

  {
    "type": "IntentRequest",
    "requestId": "amzn1.echo-api.request.9a...11",
    "timestamp": "2018-03-28T20:37:21Z",
    "locale": "en-US",
    "intent": {
      "name": "RelativeVolumeIntent",
      "confirmationStatus": "NONE",
      "slots": {
        "VolumeQuantity": {
          "name": "VolumeQuantity",
          "confirmationStatus": "NONE"
        },
        "VolumeDirection": {
          "name": "VolumeDirection",
          "value": "softer",
          "resolutions": {
            "resolutionsPerAuthority": [
              {
                "authority": "amzn1.er-authority.echo-blah-blah-blah",
                "status": {
                  "code": "ER_SUCCESS_MATCH"
                },
                "values": [
                  {
                    "value": {
                      "name": "down",
                      "id": "down"
                    }
                  }
                ]
              }
            ]
          },
          "confirmationStatus": "NONE"
        }
      }
    },
    "dialogState": "STARTED"
  }

【问题讨论】:

  • 它不是很漂亮,但你可以将它分成多行,以便索引形成一列(换句话说,视觉上堆叠它们)
  • 您还可以将嵌套字典的中间值存储在单独/有意义的变量中,这些值在前面访问过
  • davedwards - 我更新了我的问题,因为我应该说嵌套字典。我认为您链接的可能重复项是针对大型列表,但不是过度嵌套(基于我最初的措辞错误的问题,重复项将适用)

标签: python dictionary line-breaks


【解决方案1】:

首先,您可以使用一些命名良好的中间变量,让程序更易读,更简单,更快捷:

volumes = intent['slots']  # Pick meaningful names. I'm just guessing.
if 'VolumeQuantity' in volumes:
    quantity = volumes['VolumeQuantity']
    if 'resolutions' in quantity:
        half_decibels = quantity['resolutions']['resolutionsPerAuthority'][0]['values'][0]['value']['name'].strip()
    elif 'value' in quantity:
        half_decibels = quantity['value'].strip()

其次,您可以编写一个 帮助函数 nav(structure, path) 来导航这些结构,例如

nav(quantity, 'resolutions.resolutionsPerAuthority.0.values.0.value.name')

拆分给定路径并执行索引/查找操作的序列。它可以使用dict.get(key, default),这样您就不必进行太多if key in dict 检查。

【讨论】:

    【解决方案2】:

    您可能指的是嵌套字典,列表只接受整数索引。

    无论如何,(ab?)使用括号内隐含的行继续,我认为这很容易阅读:

    >>> d = {'a':{'b':{'c':'value'}}}
    >>> (d
    ...     ['a']
    ...     ['b']
    ...     ['c']
    ... )
    'value'
    

    或者

    >>> (d['a']
    ...   ['b']
    ...   ['c'])
    'value'
    

    【讨论】:

    • 你是对的,我指的是嵌套字典而不是列表。我已经更新了我的问题,并添加了我正在尝试阅读的示例 json。我不知道括号内隐含的行继续,这解决了我的问题!
    猜你喜欢
    • 2020-09-14
    • 2023-01-23
    • 1970-01-01
    • 2014-01-21
    • 2018-05-31
    • 1970-01-01
    • 2019-09-06
    • 2016-11-24
    • 2023-03-11
    相关资源
    最近更新 更多