0

i try to learn better dict in python. I am using an 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

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

obviously i misunderstood something, but i dont know what.

Thanks for your reading

1
  • games['games'] is a list so you need an index to access its element. Commented Mar 4, 2021 at 10:17

2 Answers 2

1

In your dictionary you have a key called 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 :

for game in games['games']:
  game_url = game['url']
  # your process on game_url
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer! is there a diff between your code and "print(games['games'][-1]['url'])" ?
games['games'][-1]['url'] will only get you the url of the last game. This is an important subtlety, if you receive multiple games you need to use a for loop.
Ok thanks! i understand quite better dictionnaries :)
1

Is that the entire output? I don't see the closing curly brackets (}). Either way, it seems like you can get the url like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.