简体   繁体   中英

Python - Check if value is equal to returned json response

Tell me if I'm wording this poorly. I'm calling a json response from the League of Legends API. I get back a response that looks like this.

{
"champions": [
{
    "id": 111,
    "stats": {
        "maxChampionsKilled": 2,
        "maxNumDeaths": 5,
        "mostChampionKillsPerSession": 2,
        "mostSpellsCast": 0,
        "totalAssists": 25,
        "totalChampionKills": 2,
        "totalDamageDealt": 40838,
        "totalDamageTaken": 27900,
        "totalDeathsPerSession": 5,
        "totalDoubleKills": 0,
        "totalFirstBlood": 0,
        "totalGoldEarned": 11070,
        "totalMagicDamageDealt": 21083,
        "totalMinionKills": 56,
        "totalPentaKills": 0,
        "totalPhysicalDamageDealt": 12876,
        "totalQuadraKills": 0,
        "totalSessionsLost": 1,
        "totalSessionsPlayed": 1,
        "totalSessionsWon": 0,
        "totalTripleKills": 0,
        "totalTurretsKilled": 1,
        "totalUnrealKills": 0
    }
}, 

Currently I have a list like so: champ_list[] and I have all the id's (in this case 111) in this list. So completed it would be something like champ_list[111,67,4,23], and it can keep growing up to the number of champions in the game.

I then do the following:

if '111' in champ_list:
    print("Nautilus")

Here's the question - if the above statement is true and Nautilus is printed how do I get {stats},{totalSessionsPlayed} to print its value? I realized I could add

print(['champions'][0]['stats']['totalSessionsPlayed'] 

to the end of my statement above, however if the return data doesn't stay in the same order I'm boned. Also, if the champ_list becomes very long, it would be a pain to hardcode each line. Is there a way to do this "better" or more consistent? Sorry if I'm reaching here, but any help is greatly appreciated!

Your JSON is indirectly storing an association list that maps 111 to the appropriate stat block. You should first transform this into a proper Python mapping (ie, a dict ):

json_data = { ... }
champions = {}
for d in json_data['champions']:
    champions[d['id']] = d['stats']

Now given champ_id = '111' , you can simply write

print(champions[champ_id]['totalSessionsPlayed'])

you can filter the result list for the id specified and pick the first element if it is found.

nautilus_id = 111
try:
    nautilus = filter(lambda c: c['id'] == nautilus_id, champ_list)[0]
except:
    nautilus = None

from there on you can access all data in nautilus:

print nautilus['stats']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM