Trying to count amount of occurences after a certain word from certain JSON file but am having trouble

Question:

ERROR numCraft = data[‘craft’]

KeyError: ‘craft’

I have tried to implement different counts and loops but am having trouble just count the amount of different crafts. The answer is two but just do not know how to implement or understand the concept of JSON

Asked By: gillrilla

||

Answers:

Here is a (shortened) version of the json content from that url:

{
  "message": "success",
  "people": [
    {
      "name": "Cai Xuzhe",
      "craft": "Tiangong"
    },
    {
      "name": "Chen Dong",
      "craft": "Tiangong"
    },
    {
      "name": "Anna Kikina",
      "craft": "ISS"
    }
  ],
  "number": 10
}

As you can see, the top-level items are message, people, and number. There is no top-level item named craft.

So that is why you got that error.

You probably wanted something like this:

all_crafts = set()
for person in data['people']:
    name = person['name']
    craft = person['craft']
    print(f'The astronaut {name} was in the craft {craft}')
    all_crafts.add(craft)

print('There were this many different crafts:', len(all_crafts))
Answered By: John Gordon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.