python accessing elements in a dictionary inside dictionary

眉间皱痕 提交于 2019-12-11 14:15:02

问题


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'])

回答1:


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()))


来源:https://stackoverflow.com/questions/33187121/python-accessing-elements-in-a-dictionary-inside-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!