这是我的 JSON 对象的样子:
[{
'Description': 'Description 1',
'OutputKey': 'OutputKey 1',
'OutputValue': 'OutputValue 1'
},
{
'Description': 'Description 2',
'OutputKey': 'OutputKey 2',
'OutputValue': 'OutputValue 2'
},
{
'Description': 'Description 3',
'OutputKey': 'OutputKey 3',
'OutputValue': 'OutputValue 3'
},
{
'Description': 'Description 4',
'OutputKey': 'OutputKey 4',
'OutputValue': 'OutputValue 4'
},
{
'Description': 'Description 5',
'OutputKey': 'OutputKey 5',
'OutputValue': 'OutputValue 5'
},
{
'Description': 'Description 6',
'OutputKey': 'OutputKey 6',
'OutputValue': 'OutputValue 6'
}]
如何在不循环的情况下获取 OutputKey 为 4 的字典对象?
any(key['OutputKey'] == 'OutputKey 4' for key in myJSON) 返回 true 但我需要它来获取属于该键的整个 JSON 对象。
请您参考如下方法:
你可以使用next:
next(key for key in myJSON if key['OutputKey'] == 'OutputKey 4')
但是,如果“键”不存在,您将得到一个StopIteration 异常。您可以像通常处理任何其他异常一样处理它,或者您可以为 next 提供“默认”:
default = None # or whatever...
next((key for key in myJSON if key['OutputKey'] == 'OutputKey 4'), default)
请注意,这仍然是“遍历”所有项目(除了在找到正确的项目时会短路)。如果你真的想避免循环,你需要一个不同的数据结构:
dict_by_output_key = {key['OutputKey']: key for key in myJSON}
dict_by_output_key['OutputKey 4']
您仍然需要执行 1 个循环——但是一旦完成,您可以根据需要执行任意多的 O(1) 查找。成本是一些额外的中间存储(内存)。
