gpt4 book ai didi

python - python中嵌套字典的换行代码

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:40 24 4
gpt4 key购买 nike

用新的Entity Resolution在 Alexa 中,嵌套字典变得非常嵌套。引用深层嵌套值的最 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"
}

最佳答案

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

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

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

或者替代地

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

关于python - python中嵌套字典的换行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com