Find dict that has user inputted key from a list of dicts
<p><strong>python 3.5</strong></p>

<p>hi i have this simple json.json file :</p>

<p><strong>json</strong></p>

<pre><code>{"x": [
    {"A": "B"},
    {"C": "D"},
    {"E": "F"}
]}
</code></pre>

<p>and i have this code to find the letter after A or C or E</p>

<p><strong>python</strong></p>

<pre><code>data = json.load(open('json.json'))
R = 'C' #user input
print(data['x'][1][R])
</code></pre>

<p>How can I find which dict with has the key without knowing and hard coding the index of the dict?</p>

<p>As Padraic Cunningham pointed out, you need to loop through your results. Your solution would look like this:</p>

<pre><code>data = json.load(open('json.json'))
R = 'C' #user input
print([x for x in data['x'] if x.keys()[0] == R][0][R])
</code></pre>

<p><code>[x for x in data['x'] if x.keys()[0] == R]</code> gives you all the dict with key R in a list. Assuming that you don't have repeated keys, pick the first element and access to its value.</p>

python json