python中嵌套字典的换行代码

时间:2018-03-28 21:19:07

标签: python dictionary line-breaks

使用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"
  }

2 个答案:

答案 0 :(得分:2)

您可能正在引用嵌套字典,列表只接受整数索引。

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

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

或者

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

答案 1 :(得分:0)

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

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次检查。