Scott Scott - 3 months ago 9
JSON Question

having Key Error while printing json data

python 3.5.1

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



Key Error : 'A'



python

data = json.load(...)
for item in data['x']
print (item['A'])


json

{"x":[
{"A":"B"},
{"C":"D"}
]}


whats my problem?

Answer

The problem is that your code assumes that every item in data['x'] will have a key 'A', but as soon as you iterate to a dict that does not have such a key you will get a KeyError.

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

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

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