Okay so I'm trying to get all the keys named ['species'] in the following API call from PokeAPI: https://pokeapi.co/api/v2/evolution-chain/140/
I'm not very good with JSON and since the data isn't always structured on the same list indexes, for example with this other call: https://pokeapi.co/api/v2/pokemon-species/133/ I'm not entirely sure how to get all keys named "species" as a list in the return of my function.
I can iterate through it just fine with the following code:
the response variable down below is just the apicall I linked above.
response = requests.get(self.species_url + str(self.newspeciesid))
testdata = response.json()
evochainstest = testdata['evolution_chain']['url']
chainsreq = requests.get(evochainstest)
chainsreqjson = chainsreq.json()
lengthofev = len(chainsreqjson['chain']['evolves_to'])
list = []
i = 0
while(i < lengthofev):
chainsreqparse = chainsreqjson['chain']['evolves_to'][i]['species']['name']
list.append(chainsreqparse)
i = i + 1
Is there a way to check for the name of a key in the entire dictionary, regardless of where it is and return it as a list? I'd greatly appreciate it! I have most of the webapp ready and while I get most evolutions, I am missing around 20 because of this. :(
----- UPDATE to Fireshadow52's comment
While I assume the answer given from him works, I'm not entirely sure how to apply it to my code
def test_two(self):
response = requests.get(self.species_url + str(self.newspeciesid))
content = response.json()
allids = content['id']
allevochains = requests.get(self.base_url + str(allids))
allevochainsjson = allevochains.json()
if isinstance(allevochainsjson, dict):
key = 'species'
for k, v in allevochainsjson.items():
if k == "species":
yield v
else:
yield from allevochainsjson(v, key)
elif isinstance(allevochainsjson, list):
for item in allevochainsjson:
yield from allevochainsjson(item, key)
This is what I have now and it returns it as a <generator object PokeSearch.test_two at 0x0000020E306910E0> object, did I do something wrong?