简体   繁体   English

如何在遍历数据以获取键值之前设置字典索引键?

[英]How to set dict index key before looping through data to get key,value?

Trying to parse JSON-data but having trouble to set the a dict[index] since the index variable is only present once in the JSON while the rest of the key,values requires a loop to get them.尝试解析 JSON 数据但在设置dict[index]遇到问题,因为索引变量在 JSON 中仅出现一次,而其余的键值需要循环来获取它们。 What I have tried is a nested loop, but with no success.我尝试过的是嵌套循环,但没有成功。 Getting TypeError: list indices must be integers or slices, not str .获取TypeError: list indices must be integers or slices, not str Any feedback would be highly appreciated, full example below.任何反馈都将受到高度赞赏,完整示例如下。

Many thanks,非常感谢,

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)

Expected output:预期输出:

{
    "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'],
    },
}

Your for info in info_standings only goes thru the keys in that dictionary, like in this minimal example: for info in info_standings仅通过该字典中的键,就像在这个最小的例子中一样:

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

outputs:输出:

a
b

In your code, info in that loop first got the value "label" and you then try to "label"['label'] which gives that TypeError: list indices must be integers or slices, not str .. the list being that string.在您的代码中,该循环中的info首先获得值"label" ,然后您尝试"label"['label']这给出了TypeError: list indices must be integers or slices, not str .. 列表是那个字符串.

To go thru the whole contents, do:要浏览全部内容,请执行以下操作:

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

which gives what you want:这给了你想要的:

a 1
b 2

Also, you seem to be confused about the JSON structure in the code that follows, so I was not able to fix the rest of the code easily.此外,您似乎对以下代码中的 JSON 结构感到困惑,因此我无法轻松修复其余代码。

I put it to repl.it with some print statements to see what is going on.我把它和一些打印语句放在 repl.it 中,看看发生了什么。 In general, you can print the intermediate data to see what you have, when you get problems with the parsing.通常,当您遇到解析问题时,您可以打印中间数据以查看您拥有的数据。 You can run my bit improved version of your code there.你可以在那里运行我的代码的改进版本。 If you fix it further but get more problems, I can try helping again.如果您进一步修复它但遇到更多问题,我可以再次尝试提供帮助。 https://repl.it/@ToniAlatalo/WingedSubduedDisk https://repl.it/@ToniAlatalo/WingedSubduedDisk

@DanielP helped solve this be informing me that Python dictionaries must have unique keys, in me expected output I would have the key "2019/20" twice. @DanielP 帮助解决了这个问题,它告诉我 Python 词典必须有唯一的键,在我预期的输出中,我将有两次键“2019/20”。

So by changing the "index variable" in the dictionary it worked smoothly.因此,通过更改字典中的“索引变量”,它可以顺利运行。

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()

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

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