#๐Ÿ”’ Can I make key-value pairs from an api json object into an dictionary?

7 messages ยท Page 1 of 1 (latest)

autumn glen
#

Hi, I made a function out of the json object. The problem is that I get all of the key value pairs at once if I put "return gameday_data". I can't return the key value pairs separately, at least not without making several functions. Is it possible to turn these into a dictionary so I can return all of them and "pick them out" seperatly when I need them? The hashtaged parts is what I tried to do that didn't work.

I'm in a beginner course for python so this is all pretty new.

Here's the code in text:
def get_gameday():
gameday_url = f'{base_url}/api/{season}/{gameday}'
gameday_data = requests.get(gameday_url).json().get('games',{})
for game in gameday_data:
#score = game.get('score')
#home = score.get('home')
#home_team = home.get('team').split(' ')[0]
#home_goal = home.get('goals')
#away = score.get('away')
#away_team = away.get('team').split(' ')[0]
#away_goal = away.get('goals')
#return score, home_team, home_goal, away, away_team, away_goal

hearty oliveBOT
#

@autumn glen

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

verbal sand
#

Those are already a dictionary. When you do .json() on the returned info, it converts the json string into python objects - including dictionaries, all those .get on stuff are dict.get method

So you in fact want to convert one dictionary into another dictionary.

#

+Please remember that return ends the function, so you probably want to save all games into a list.

So I'd do it this way:

result = []
for game in gameday_data:
    # for each game, make a new dictionary only with info you want
    score = game["score"] # direct indexing as we know it has to exist(?) 
    home = score["home"] 
    game_info = {
        "home_team": home["team"].split()[0],
        "home_goal": home.get("goals"),
        # add more keys and values here
    }
    results.append(game_info)

return results # has to be outside of the loop

Note that I did direct dict indexing when key seems to must exist - dict.get returns None when the key isn't found, so .get or .split would error in those cases, so I assumed they must always exist.

The results I created is a list of dicts

autumn glen
hearty oliveBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.