Home > OS >  Trying to count amount of occurences after a certain word from certain JSON file but am having troub
Trying to count amount of occurences after a certain word from certain JSON file but am having troub

Time:10-28

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

CodePudding user response:

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))
  • Related