简体   繁体   English

如何解析 python 中的字典

[英]How to parse a dict in python

i try to learn better dict in python.我尝试在 python 中学习更好的 dict。 I am using an api "chess.com"我正在使用 api “chess.com”

 data = get_player_game_archives(username).json


    url = data['archives'][-1]
    games = requests.get(url).json()

    game = games['games'][-1]
    print(games)

That's my code and they are no problem and the result is那是我的代码,它们没问题,结果是

{'games': [{'url': 'https://www.chess.com/live/game/8358870805', 'pgn': '[Event "Live Chess"]\n[Site "Chess.com"]\n

But i dont know how to get the "url", i tried但我不知道如何获取“url”,我试过了

    game = games['games']['url'] or
       game = games['games'][{url}]

obviously i misunderstood something, but i dont know what.显然我误解了一些东西,但我不知道是什么。

Thanks for your reading感谢您的阅读

In your dictionary you have a key called games .在您的字典中,您有一个名为games的键。 The value associated to this key is a list of dictionaries (it starts with [{ ) You need to loop on all the games as follows, assuming your dictionary is stored in the variable games :与此键关联的值是字典列表(它以[{开头)您需要按如下方式循环所有游戏,假设您的字典存储在变量games

for game in games['games']:
  game_url = game['url']
  # your process on game_url

Is that the entire output?那是整个output吗? I don't see the closing curly brackets ( } ).我没有看到右大括号 ( } )。 Either way, it seems like you can get the url like:无论哪种方式,您似乎都可以获得 url ,例如:

url = games['games'][0]['url']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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