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>So you want to find the value by searching without hard coding the index, what you need is a loop that checks each dict for the key:</p>

<pre><code>data = json.load(open('json.json'))
R = 'C' #user input
for d in  data['x']:
    if R in d:
        print(d[R])
        break # if there can be more that one match then remove
</code></pre>

python json