【发布时间】: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