Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Joyce van den Berg
Joyce van den Berg
10,684 Points

Getting data from api in json format into a python dictionary

It's an unusual question that does not stem from my coursework here, but maybe someone can help me think through this.

I have to get information from an api and catch it in a python dictionary. The api is a url plus a page number. I will then use that dict to get information to a database, which I am pretty sure I can do. I am looking for the best way to get a few key-value pairs from the json format to do that.

Can I capture specific key-value pairs? Should I get all of it in a dict? And am I doing it the right way? (I am getting the full load in a dict, but it's full of data I dont need!)

import mysql.connector
import requests
import json

# I need a dictionary to catch all the names, id, weight and height in.\
pokemon = {}
poke_url = "https://pokeapi.co/api/v2/pokemon/"
print(poke_url)

poke_page = 0
for number in range(0,151):
    poke_page += 1
    answer = requests.get(poke_url + str(poke_page))
    pokemon_tabel = json.loads(anwer.text)

for item in pokemon_tabel:
    name = pokemon_tabel.get("name")
    weight = pokemon_tabel.get("weight")
    height = pokemon_tabel.get("height")
    poke_id = pokemon_tabel.get("id")

# connect met db / or create one

# create table 

# insert data in table

#commit and close connection to database - commented out for now
#mydb.commit()
#mydb.close

Thanks for looking at this! All help appreciated :)

[MOD: added ```python formatting -cf]

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

If just looking to limit the unwanted data and you know the specific items you wish, say, by name, you could add a check after the name assignment:

if name not in accepted_list:
    # continue for loop with next item
    continue

the define accepted_list before the for loop.

you could add other selections based on the other attributes weight, height, poke_id

Post back if you need more help. Good luck!!!

Joyce van den Berg
Joyce van den Berg
10,684 Points

Thanks! I ended up doing it way way differently, though. I created a new dictionary in the loop for all the key-value pairs I needed and inserted that single dictionary into the database before looping again and creating a new dictionary with new key-value pairs. It was not elegant, but in the end it worked.