fuhrerguxez fuhrerguxez - 1 year ago 206
Python Question

Python - Find value from Json

First off, I'm sorry for the title, I didn't know how to be specific about my issue there.

Ok, I'm doing something with the League of Legends API. The data is displayed as Json and it can be found here, what I want to do is loop through it. I have data from another script that displays stats from each player on a match. In those stats there is an id with the champion being played. I want to use that Id and compare with each key from the json file above and if it finds a matching key - id I can get the name of the champion. My problem is that I don't know exactly how I can iterate through each one of them, because as you can see on the file there is THIS (Posted an image because I couldn't get the indent right.

How can I access the Id of each one? Because, again, as you can see, each one has different names (Jax, Sona, Tristana, etc...) I just want the key and Name of each one. I tried using a For loop but couldn't even list the first one so I'm pretty lost this time. Thanks for any help :)


champ_r = requests.get("https://global.api.pvp.net/api/lol/static-data/lan/v1.2/champion?"

for x in champ_r['data'][0]:

If I run it like that I get a
KeyError: 0
and if I remove it I get
TypeError: string indices must be integers

As an output I would like it to return the Ids and Names of each one of the champions. Something like:

Aatrox - Key
Ahri - Key...

... and so on.

Answer Source

Based on the sample output you are trying to get, the "key" of your dictionary is actually the name you are looking for, and the value associated with that key is a dictionary. You are looking for the "key" key in that dictionary. So, when you are iterating over the dictionary, your value is actually a dictionary. You can make your iteration easy on you, by using the items method in your iteration.

Furthermore, all your data is stored in the "data" key from your big json response. So, your code should look like this:

for key, value in champ_r['data'].items():
    print(key, value['key'])

Sample output of the first few lines:

Sona 37
Draven 119
FiddleSticks 9
Volibear 106
Pantheon 80
Singed 27
Vladimir 8
Ekko 245
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download