Asdfg Asdfg - 1 year ago 59
Python Question

select dict object based on value

This is how my JSON object looks like:

'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'

How do i grab the dict object where OutputKey is 4 without looping thru?

any(key['OutputKey'] == 'OutputKey 4' for key in myJSON)
returns true but i need it to grab the whole JSON object that belongs to that key.

Answer Source

You can use next:

next(key for key in myJSON if key['OutputKey'] == 'OutputKey 4')

However, if the "key" isn't present, then you'll get a StopIteration exception. You can handle that as you normally would handle any other exception, or you can supply a "default" to next:

default = None  # or whatever...
next((key for key in myJSON if key['OutputKey'] == 'OutputKey 4'), default)

Note that this is still "looping through" all the items (except that it short circuits when it finds the right one). If you really want to avoid a loop, you'll need a different data-structure:

dict_by_output_key = {key['OutputKey']: key for key in myJSON}
dict_by_output_key['OutputKey 4']

You still have to do 1 loop -- But once you've done it, you can do as many O(1) lookups as you want. The cost is a little additional intermediate storage (memory).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download