Home > OS >  How to access a field that is always in the same position, but has a different name?
How to access a field that is always in the same position, but has a different name?

Time:08-08

I am playing around with some soccer matchdata that is in JSON format, saved in the variable "matches" via

with open('path') as json_data:
    matches = json.load(json_data)

The following is an excerpt of the data for match number 1 (gained via "matches[1]":

{
  "status": "Played",
  "roundId": 4405517,
  "gameweek": 34,
  "teamsData": {
    "2482": {
      "scoreET": 0,
      "coachId": 272299,
      "side": "home",
      "teamId": 2482,
      "score": 3,
      "scoreP": 0,
      "hasFormation": 1,
      "formation": {
        "bench": [

The name of the field "2482" is the ID of one of the two teams playing in the match (the other one follows later, but providing the whole match data for for even one match would make this post far too long). The data goes on like this (306 matches, 2 teams each), i. e. the field is always in the same position in the data. Since the field's name is always different, however, I am struggling to access it for e.g. game number 20 without looking up the team's ID first since

match[20]['teamsData'][1]

does not work ("KeyError: 1").

Can anyone help me out?

CodePudding user response:

You can think of a dictionary as an index, and in your case you could just reindex the data with a more convenient value. If "side" is always either "home" or "away", you can use that known value instead of the variable team id value.

In this example, "teamsData" is replaced with a reindexed dictionary.

for match in matches:
    match["teamsData"] = {value["side"]:value for value in match["teamsData"].values()}

matches[20]["teamData"]["home"]
  • Related