简体   繁体   中英

python accessing elements in a dictionary inside dictionary

I get a response from riot's server:

def main():
    api = RiotAPI('dec34559a91-ad8b-4fd2-b49a-bae3b4524522b8a')
    summoner_name = str(input("Please enter the summoner ID\n"))
    if summoner_name == "":
        summoner_name = "zLKida"
    r = api.get_summoner_by_name(summoner_name)
    print(r)

which prints out something like this:

{'zlkidda': {'profileIconId': 539, 'id': 27003987, 'summonerLevel': 30, 'name': 'zLKidda', 'revisionDate': 1444958792000}}

I have no idea how I can access the data inside the dictionary. Note that it is returned as a dict not a string or anything else.

I have tried:

print(r['zlkidda'].['profileIconId'])

Remove the dot:

print(r['zlkidda']['profileIconId'])

or for your code specifically, reusing teh summoner_name variable:

print(r[summoner_name]['profileIconId'])

You are using subscriptions here; the [...] selects one element from the container.

. notation on the other hand, is used for attribute referencing , use that for things like dict methods:

print(list(r['zlkidda'].keys()))

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