select dict object based on value
<p>This is how my JSON object looks like:</p>

<pre><code>[{
    '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'
}]
</code></pre>

<p>How do i grab the dict object where OutputKey is 4 without looping thru?</p>

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

<p>You can use <code>next</code>:</p>

<pre><code>next(key for key in myJSON if key['OutputKey'] == 'OutputKey 4')
</code></pre>

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

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

<p>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:</p>

<pre><code>dict_by_output_key = {key['OutputKey']: key for key in myJSON}
dict_by_output_key['OutputKey 4']
</code></pre>

<p>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).</p>

python