Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading