Как установить ключ индекса dict перед циклом по данным, чтобы получить ключ, значение? - PullRequest
0 голосов
/ 08 февраля 2020

Пытается проанализировать JSON -данные, но не может установить a dict[index], поскольку переменная индекса присутствует только один раз в JSON, в то время как остальные ключи, значения требуют, чтобы al oop получил их , Я попробовал вложенное l oop, но безуспешно. Получение TypeError: list indices must be integers or slices, not str. Любая обратная связь будет высоко оценена, полный пример ниже.

Большое спасибо,

class Premier_league:

    def __init__(self, base_url='https://footballapi.pulselive.com/football'):
        self.base_url = base_url

    def get_standings(self, compSeasons):

        url = self.base_url + '/compseasons/{}/standings'.format(compSeasons)
        print(url)
        # url -> https://footballapi.pulselive.com/football/compseasons/274/standings

        params = (
            ('pageSize', '100'),
                )
        response = requests.get(url, params = params).json() # request to obtain the team info

        all_standings = response["tables"][0]['entries']
        info_standings = response['compSeason']


        standings = {} #Store all standings


        #loop to get all info for all standings
        for info in info_standings:
            standing_id = info['label']
            index = standing_id
            standings[index] = \
                {'id' : info['id']}
            for standing in all_standings:
                standings[index] = \
                {
                'team' : standing['team']['name'],
                'team_id' : standing['team']['club']['id'],
                'position' : standing['position'],
                'overall' : standing['overall'],
                'home' : standing['home'],
                'away' : standing['away'],
                }

        f = open("standings_" + str(compSeasons) + ".json","w")

        # pretty prints and writes the same to the json file 
        f.write(json.dumps(standings,indent=4, sort_keys=False))
        f.close()

if __name__ == "__main__":
    prem = Premier_league()
    prem.get_standings(274)

Ожидаемый результат:

{
    "2019/20": {
                'id' : info['id']
                'team' : standing['team']['name'],
                'team_id' : standing['team']['club']['id'],
                'position' : standing['position'],
                'overall' : standing['overall'],
                'home' : standing['home'],
                'away' : standing['away'],
    },
    "2019/20": {
                'id' : info['id']
                'team' : standing['team']['name'],
                'team_id' : standing['team']['club']['id'],
                'position' : standing['position'],
                'overall' : standing['overall'],
                'home' : standing['home'],
                'away' : standing['away'],
    },
}

Ответы [ 2 ]

0 голосов
/ 08 февраля 2020

@ DanielP помог решить эту проблему, сообщив мне, что в словарях Python должны быть уникальные ключи, во мне ожидаемый результат, у меня будет ключ "2019/20" дважды.

Таким образом, изменяя «переменную индекса» в словаре, она работала гладко.

def get_standings(self, compSeasons):

    url = self.base_url + '/compseasons/{}/standings'.format(compSeasons)
    print(url)

    params = (
        ('pageSize', '100'),
            )
    response = requests.get(url, params = params).json() # request to obtain the team info

    all_standings = response["tables"][0]['entries']
    season_id = response['compSeason']['id']


    standings = {} #Store all standings


    #loop to get all info for all standings
    for standing in all_standings:
        standing_id = standing['team']['name']
        index = standing_id

        standings[index] = \
        {
        'season_id' : season_id,
        'team_id' : standing['team']['club']['id'],
        'position' : standing['position'],
        'overall' : standing['overall'],
        'home' : standing['home'],
        'away' : standing['away'],
        }


    f = open("standings_" + str(compSeasons) + ".json","w")

    # pretty prints and writes the same to the json file 
    f.write(json.dumps(standings,indent=4, sort_keys=False))
    f.close()
0 голосов
/ 08 февраля 2020

Ваш for info in info_standings проходит только через ключи в этом словаре, как в этом минимальном примере:

for v in {'a': 1, 'b': 2}:
    print(v)

выводит:

a
b

В вашем коде info в что l oop сначала получил значение "label", а затем вы пытаетесь "label"['label'], что дает TypeError: list indices must be integers or slices, not str .. список, являющийся этой строкой.

До go через все содержимое, выполните :

for key, value in {'a': 1, 'b': 2}.items():
    print(key, value)

, который дает то, что вы хотите:

a 1
b 2

Кроме того, вы, кажется, не понимаете структуру JSON в следующем коде, поэтому я не смог легко исправить оставшуюся часть кода.

Я поместил его в repl.it с некоторыми инструкциями печати, чтобы увидеть, что происходит. В общем, вы можете распечатать промежуточные данные, чтобы увидеть, что у вас есть, когда у вас возникнут проблемы с анализом. Вы можете запустить мою немного улучшенную версию вашего кода там. Если вы исправите это дальше, но получите больше проблем, я могу попробовать помочь снова. https://repl.it/@ToniAlatalo / WingedSubduedDisk

...