having Key Error while printing json data
<p><strong>python 3.5.1</strong></p>

<p>hi i have following json and python code and i want to print json data but it has an error that says:</p>

<blockquote>
  <blockquote>
    <p>Key Error : 'A'</p>
  </blockquote>
</blockquote>

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

<pre><code>data = json.load(...)
for item in data['x']
    print (item['A'])
</code></pre>

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

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

<p>whats my problem?</p>

<p>As @elethan pointed the second item would not have key <code>'A'</code></p>

<p>You can do the following</p>

<pre><code>data = json.load(...)
for item in data['x']:
    print(item.get('A'))
</code></pre>

<p>That would not get any error for your specific json input, and print <code>None</code> if it won't find <code>'A'</code> key in element.</p>

<p>You can also supply default value to <code>.get()</code>, e.g. <code>item.get('A', 'default')</code>.</p>

<p>Thanks @elethan</p>

python json