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>The problem is that your code assumes that every item in <code>data['x']</code> will have a key <code>'A'</code>, but as soon as you iterate to a <code>dict</code> that does not have such a key you will get a <code>KeyError</code>.</p>

<p>Try using <code>item.get('A')</code> which will return <code>None</code> (or a default you provide) if there is no key <code>'A'</code> in your dictionary. It seems like you want to do something like this:</p>

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

<p>This will print the value associated with the key <code>'A'</code> if it exists, otherwise it will move on to the next dictionary in the list.</p>

python json